0

fields: (Date to - Date from) = Total Number of Days

How can I compute the total number of days between two dates using Computed Field?

2 Answers 2

1

Here is a sample snippet (to be used in Computed Code PHP Block inside of a computed field)

$food_date_value = array_pop(field_get_items($entity_type, $entity, 'field_food_date'));
$food_date = new DateObject($food_date_value['value'], '');
$current_date = new DateObject('now', '', 'm/d/Y');
$entity_field[0]['value'] =$food_date->difference($current_date, 'days');

field_food_date is a date in the Unix Timestamp format (another field in my content type). DateObject can then be used for doing any date calculations.

7
  • Thanks! but what if the date is not the current date? I also use a pop calendar.
    – noob
    Apr 7, 2014 at 4:49
  • You can feed in the other date similar to how $food_date is constructed
    – rajasaur
    Apr 7, 2014 at 5:02
  • Here is my code and it's not working :( $start_date = array_pop(field_get_items($entity_type, $entity, 'field_date_from')); $end_date = array_pop(field_get_items($entity_type, $entity, 'field_date_to'));) $start_date = new DateObject($start_date['value'], ''); $end_date = new DateObject($end_date['value'], ''); $entity_field[0]['value'] =$start_date->difference($end_date, 'days');
    – noob
    Apr 7, 2014 at 5:16
  • What format are your field_date_from and fielddate_to ? They have to be Unix timestamp based or an array consisting of the keys "year", "date", "month"
    – rajasaur
    Apr 7, 2014 at 8:37
  • Hurrray! I did it. I solved the error. Thanks for your help :)
    – noob
    Apr 15, 2014 at 2:03
0

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

$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

$display_output = $entity_field_item['value'];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.