drupal 7

ArticleCalculate a duration between dates in Drupal 7.

For a small project I'm working on I need to log the amount of hours I spend on it. The internet lists a great number of applications which can achieve this, but either they cost a lot of money are are bloated far beyond my needs.

Luckily I have some Drupal experience, so I quickly put together a content type with a title, and a date field that contains a start and an end date. Using views I also quickly created a table which provides an overview. It looks something like the following:

project name setup, theming 2011/09/19 - 09:00 to 17:30 8.5

The last column was the tricky one. I wanted to show the actual number of hours for the specified period. Luckily, there's a module for that: Computed Field. Assume the field that contains the date is called field_datefield the following computed field configuration can be used:

Computed code

  1. $start_value = $entity->field_datefield[LANGUAGE_NONE][0]['value'];
  2. $end_value = $entity->field_datefield[LANGUAGE_NONE][0]['value2'];
  3. $timezone = $entity->field_datefield[LANGUAGE_NONE][0]['timezone'];
  4.  
  5. $start_date = new DateObject($start_value, $timezone);
  6. $end_date = new DateObject($end_value, $timezone);
  7.  
  8. $duration = $start_date->difference($end_date, 'hours');
  9. $entity_field[0]['value'] = $duration;

Display code

  1. $display = $node_field_item['value'];

In order to use this in a views table we also need to store the field in the database. So enable the save functionality and enable the following:
Data type: float
Data length: 5,2