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".

Comments

Rosamunda’s picture

Could this (something similar) be applied to money to pay calculating the total debt with a certain interest rate?
It could be between dates calculated in months...

StuartDH’s picture

Anyone know how to make this work in D6?

hawkbreeze’s picture

Yes I spent a couple of hours getting it working with D6.
I changed the code a bit to make it more flexible.

Here is the computed code.
NOTE: change "$node->field_datefield" to the field name of your date field.

# Get the values from $node
$start_value = $node->field_datefield[0]['value'];
$end_value = $node->field_datefield[0]['value2'];
$timezone =  $node->field_datefield[0]['timezone'];
$type = $node->field_datefield[0]['date_type'];

# Get a date object from the values
$start_date = date_make_date($start_value, $timezone, $type);
$end_date = date_make_date($end_value, $timezone, $type);

# Call the date_difference function to get the difference between the two dates. Note you can specify the duration measure, either years, months, weeks, days, hours, minutes or seconds. I am using hours. The following line is taken from the date_difference function.
# date_difference($date1_in, $date2_in, $measure = 'seconds', $type = DATE_OBJECT)

$duration = date_difference($start_date, $end_date, 'hours');
$node_field[0]['value'] = "$duration";

And the display code.

$display = $node_field_item['value'];

Store in database.
Data type: float
data Length: 5,2
Sortable = checked.

sphopkins’s picture

Is it possible for this code to work on two fields where one is a datetime field and one is a date field?

Ralf Saalmueller’s picture

Hello cannod,

hope you can help. I used your code and it is working. Great.

But I'm in need to alter one of the datefield values and lack the basic coder know how. How to I store a date? Even this simple, untouched copy doesn't work:
: $start_value = $node->field_datefield[0]['value'];
: $node_field[0]['value'] = $start_value;

Is it possible to handle datefields? How do handle multiple values. What is the display code for multiple data?

Background: My users found a way to misuse the setup as they cheat by enter a start value in the past just to get on top of the list. I like to correct that by compute the max($start_value, today), so all nodes have the same start date when the event already started.

All in all:
: Read two values from a multiple value datefield in start_date and end_date;
: if (end_date > today)
: : if (start_date < today) start_date = today endif
: endif
: Return a result with two values: start_date & end_date

I'm a little bit ashamed that I can't write the php code for that. Sorry, I'm at the very beginning.

ThanX, Ralf

llorberb’s picture

is there a way to vary the out put format

for instance.

in days if duration is <1.5 weeks
in weeks if duration in <2 months
in months id duration is < 2 months

Thanks,
Lauren

j.somers’s picture

Following code is the D7 equivalent of the above D6 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;
kaizerking’s picture

This code worked for me ,I have multiple durations (multi value field collection item) how to add up and display the sum in another field?
ex:Duration1=10 months
Duration2=12 months
Total duration=22 months

kaizerking’s picture

calculating the duration worked out using the computed field
I have requirement to
1.sum up all the durations in a work experience field collection in resume,
help me please pl.
2. Calculate the duration from the oldest start date to Date Now()
help please
have look at screen shot

colan’s picture

Looks good, but field_get_items() should be used instead of digging into the field directly.

Umayal’s picture

I want to calculate the days between the from and to date.
the following code does not calculate the days
I have the value start and end date.
when i calculate date the Page displayed blank with ... (Object) DateInterval

$start = new DateTime($st->field_fdt_period_timing['und'][0]['value']);
$end = new DateTime($st->field_fdt_period_timing['und'][0]['value2']); 
$diff = $end->diff($start);
$a=$diff->days;
dpm($a);
aniket.mohite88’s picture

If the Machine name of your date-field is 'field_example_date', then the Computed Code (PHP) would be

<?php
$startdate = $entity->field_example_date['und'][0]['value'];  

// Value of start-date
$enddate = $entity->field_example_date['und'][0]['value2'];  
// Value of end-date


$datediff = strtotime($enddate) - strtotime($startdate);
// The PHP Function STRTOTIME parses the english textual datetime description into a Unix timestamp

$num_leaves = $datediff/(60*60*24);
/* Since we need the number of days IN-BETWEEN, we divide the resultant difference by 60*60*24 . 
 *
 * Incase of counting no.of days "FROM" to "TO" days, add 1 to the above result.
 * $num_leaves = $datediff/(60*60*24) + 1;
 */

$entity_field[0]['value'] = $num_leaves;
?>

The Display Code (PHP) will have

<?php
$display_output = $entity_field_item['value'];
?>

Notes -

  • Please exclude the PHP tags while, entering the codes in computed field settings
  • More info on strtotime()
  • Any field on a given node for computed field is referenced MOSTLY by $entity->fieldname. Take help of devel & dpm()

My Requirement was to calculate the no of days a leave-request was applied for based on the start & end dates.
So even if its a one day leave, a start date would have to be entered surely & where an end date would be skipped.

In that case, alter code

<?php
if(!empty($entity->field_leave_app_date['und'][0]['value2'])) {
   $enddate = $entity->field_leave_app_date['und'][0]['value2'];
 }
else {
  $enddate = 0;
}
?>
arzuga’s picture

using that code everything work
Today I was working on my site and I added a new content where:
where start is 2015-03-27T00:00:00
and the end is 2015-03-31T00:00:00

the result is 2.95833333333

why ?

Thanks

de3pimpact’s picture

Hi

I am having trouble using the code for computed field. I am using Drupal 6.

I have defined two fields:
field_d1
field_d2
and both of them are date fields using KarenS' Date module.

I have used both the code in this page, and cannod's code. But none seem to be working!

Could anyone please help. Appreciate it.

Thanks

emilyf’s picture

You can just do this if you're using a single date field with from/to values:

$node_field[0]['value'] = date_difference($node->field_your_date_field[0]['value'],$node->field_your_date_field[0]['value2'], 'hours',DATE_DATETIME);

or this if you have 2 separate date fields:

$node_field[0]['value'] = date_difference($node->field_your_date_field[0]['value'],$node->field_your_other_date_field[0]['value'], 'hours',DATE_DATETIME);

you can specify 'seconds', 'minutes', 'hours' or 'years' in the third parameter for what you want your value displayed as.

mohd hazreen’s picture

Can anybody help me with this.I want to calculate duration for working hours on certain ticket only.For example the duration start at from 9am until 5pm a day.Then exclude Saturday and Sunday.Currently the duration calculate from the start date until end date including off working hours and that is not so precise.Can anybody gift me guide or anything.

mohd hazreen’s picture

i need to calculate duration between post date and last comment time. i have the code right here..but the code doesn`t working. so i was hoping someone can help me

$start_value = $node->created[0]['value'];
$end_value = $node->last_comment_timestamp[0]['value'];
$timezone = $node->last_comment_timestamp[0]['timezone'];
$type = $node->last_comment_timestamp[0]['date_type'];

$start_date = date_make_date($start_value, $timezone, $type);
$end_date = date_make_date($end_value, $timezone, $type);

$exacthour = date_difference($start_date, $end_date, 'hours');

$node_field[0]['value'] = "$exacthour"

hazreen..

flexator’s picture

Hi, i want to have the duration of start and end date in weeks, not for 2 different datefields, just by the "add another date" button
1.date 16 weeks
2.date 4 weeks
and so on.

when i use the code for D7 from above:

<?php
$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;
?>

and for the output this one

$node_field[0]['value'] = date_difference($node->field_your_date_field[0]['value'],$node->field_your_date_field[0]['value2'], 'weeks',DATE_DATETIME);

it shows me in both fields the result from the first field i entered (16 weeks).
Am I stupid or just didn`t read enough howtos? How should i do this?

kaizerking’s picture

How to get the difference in months and also if i want to get some thing like 3.5 years?

joaomachado’s picture

This worked perfect for two date fields in my content type unless you only have one field, then it gives a fatal error. How would I tell it not to compute if the two dates were not there? I tried checking the "Not NULL" box to no avail.

Joao

"when the only tool you have is a hammer, all problems start to look like a nail"

deelite’s picture

Is there a final solution to calculate the end time given the start time and duration?

That would be great!

tribe_of_dan’s picture

I have a start date in a CCK Date field and an Integer field for days that I want added to the start date. I want to calculate the end date based on Start Date + Days.

Can anybody help?

glennnz’s picture

Does anyone have a solution for this for the D7 version?

Glenn
THECA Group

joaomachado’s picture

A bit of a newbie with PHP...trying to calculate difference in days between today and a given date from date field.
Any help would be appreciated..

John

"when the only tool you have is a hammer, all problems start to look like a nail"

AtomicTangerine’s picture

That function and static variable will return Unix timestamps. They are different though, use the appropriate one according to your needs. That should get you your "to date" that you need to be automatic. I'm a newbie too, just found that function and variable today, hope it helped.

joaomachado’s picture

Thanks, I will try it!

"when the only tool you have is a hammer, all problems start to look like a nail"

llorberb’s picture

I would like to do the following:

If To date - from date =
5 days --> "Less than 1 Week'
10 days --> '1 to 2 Weeks'
30 days --> "One Month"

I also need these fields to be searchable in the form of a drop down list which I believe may limit my options for implementing this.

Any ideas...

Thank You!

videographics’s picture

Any chance we can update this so that it will work in D7? So much has changed we need to do a lot more than simply change node to entity...

augustynen’s picture

Oké, I had DATE (ISO FORMATE) and that returned nothing.
Now i have selected just date and finely something displays (I also had to add [LANGUAGE_NONE]).

Computed Code (PHP)

<?php
$field_info = array_pop(field_get_items($entity_type, $entity, 'field_date'));

$start = $field_info[LANGUAGE_NONE][0]['value'];
$end = $field_info[LANGUAGE_NONE][0]['value2'];
$timezone = $field_info[LANGUAGE_NONE][0]['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 (PHP)

<?php
$display_output = $entity_field_item['value'] . " uur";
?>

Still I have a problem: It show O hours.

I guess I know why, I don't only store time but also date ('cause things can happen overnight).
I think there is a problem with calculating that?

How do I tweak the code on top to work for let's say:

22:00 hours day 1 to 03:00 hours day two... ?

Thanks for all the help !

iwd35’s picture

hello,
i have two date on webform (drupal 7) , first field:alis_tarihi then second field: iade_tarihi.
i want to calculate difference between two days but hours are not important for me (like: difference is 3 days) .
how can i do it?pls help me.

thx

dollepret’s picture

Hi, I was wondering if you ever got this to work? I'm running into the same problem at the moment and I can't seem to get it to work. Thanks!

vmevada102’s picture

I had used the above said example. but now my content type has the data and not able to delete or add any field in it.

I had created the experience field in content type in the Multifield table module.

Now would like to calculate the difference using Views PHP module.

But could not calculate using the details

COdes in "Output Code"

<?php

$start_value = $row->field_experience_faculty_field_duration_exp_value;
$end_value = $row->field_experience_faculty_field_duration_exp_value2;

$start_date = new DateObject($start_value);
$end_date = new DateObject($end_value);
$duration = $start_date->diff($end_date);


echo $duration;

?>
vmevada102’s picture

I had created the views and Put code in output code in Global: PHP.. But could not calculate the information needed.

Kindly help me to solve this problem as needed.


$start_value = $row->field_experience_faculty_field_duration_exp_value;
$end_value = $row->field_experience_faculty_field_duration_exp_value2;

$start_date = new DateObject($start_value);
$end_date = new DateObject($end_value);
$duration = $start_date->diff($end_date);


echo $duration;

Myna91’s picture

Hello sir,
I am using spreadsheet input option for time entries,but when i am fetching details from the views the Time format like 9:45:00 is converted to 0.40625 which is divided by 24,i don't know what is the problem behind this and why the time field is getting divided by 24 while retrieving from DB.Please help me on this....I will be very much grateful....

Thanks in Advance.

vmevada102’s picture

Kindly visit the following post for the detailed information

https://www.drupal.org/node/2783083

jasperlevi’s picture

xxx

jasperlevi’s picture

Is there a way to do the reverse of what is being done here? I mean, is it possible to have a field where I input the duration of the event, as well as the start date+time, and the end date+time is automatically set, using the duration of the event. If there is a way to do this, it would greatly help me with a class management system that I am trying to build using this module.

Thanks.