Calculate 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 description time hours
example 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

$start_value = $entity->field_datefield[LANGUAGE_NONE][0]['value'];
$end_value = $entity->field_datefield[LANGUAGE_NONE][0]['value2'];
$timezone = $entity->field_datefield[LANGUAGE_NONE][0]['timezone'];
$start_date = new DateObject($start_value, $timezone);
$end_date = new DateObject($end_value, $timezone);
$duration = $start_date->difference($end_date, 'hours');
$entity_field[0]['value'] = $duration;

Display Code

$display_output = $entity_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
comments powered by Disqus