Advertising sustains the DA. Ads are hidden for members. Join today

Computed Field

Calculating a duration given a start and end time

Last updated on
30 April 2025

This example uses KarenS' Date module to create a date field, "field_date", with both a start time and an end time that records hours and minutes. We then create a new computed field to calculate the duration as a decimal number of hours (where 1.5 is 1 hour and 30 minutes).

Computed field settings

  • Computed Code:
    $field_info = array_pop(field_get_items($entity_type, $entity, 'field_date'));
    
    $start = $field_info['value'];
    $end = $field_info['value2'];
    $timezone = $field_info['timezone'];
    
    $date_start = new DateTime($start, $timezone);
    $date_end = new DateTime($end, $timezone);
    
    $interval = $date_start->diff($date_end);
    
    $entity_field[0]['value'] = $interval->format('%h');
    
  • Display Code:
    $display_output = $entity_field_item['value'] . " hours";
    
  • Check "Store using the database settings below".
  • Data Type: float
  • Data Length: 3,2

Now if you set the start time field to 0900h and the end time to 1130h, your computed field will store the value "2.5" and display "2.5 hours".

Help improve this page

Page status: Not set

You can: