Drupal Date Manipulation

An easier way of getting difference between dates is achieved using the DateObject provided by Drupal.

<?php
$now_date
= date_now();
$last_donation_date = new DateObject($node->field_date[LANGUAGE_NONE][0]['value'], 'UTC');
// Get difference in days in positive if $now_date is greater than $last_donation_date
$diff_days = $last_donation_date->difference($now_date, 'days', FALSE);
?>

Print a Date Object in any format using date_format_date:

<?php
print date_format_date($date_object, 'custom', 'Y m d');
?>

--
Source
http://drupalcontrib.org/api/drupal/contributions!date!date_api!date_api...
http://www.drupalcontrib.org/api/drupal/contributions!date!date_api!date...
https://drupal.org/node/1364744
Earlier PHP Date Tutorial: http://dhongibaba.jagriti.co.in/content/dates-using-php

Technologies: 

Comments

Some important things while using this code.

The following line gives absolute difference in dates:
$diff_days = $last_donation_date->difference($now_date, 'days'); //Get difference in days

Use the third argument to get the actual difference with signs.
$diff_days = $last_donation_date->difference($now_date, 'days',FALSE);

Also, since we might use the same difference function to calculate the difference in seconds, another parameter must be kept in mind.
If you are saving the field in site timezone, as we usually do, we must get the date object made wrt to the UTC.
Therefore use the function like:

$last_donation_date = new DateObject($node->field_date[LANGUAGE_NONE][0]['value'], 'UTC');

Cheers,
Rajat