PHP - How to calculate the difference between two dates in PHP?

No replies
shashwat
Offline
Last seen: 1 year 31 weeks ago
Joined: 2009-02-18
bOt Points: 1160

It is very easy to calculate difference between any two given dates in PHP >= 5.3. We can use in-built DateTime class of PHP for this purpose.

I will explain below how to do this:

Create two objects of PHP DateTime class, say $date_first and $date_second, as shown below:

<?php

//date_default_timezone_set('UTC');
/** Uncomment the above line if you get any error **/

$date_first = new DateTime("2013-03-15");
$date_second = new DateTime("2012-07-20");

?>

Next, we can use diff() method of PHP DateTime class to calculate the actual difference:

<?php

$diff = $date_second->diff($date_first);
echo '<pre>' . print_r($diff, true) . '</pre>';

?>

The output of the above code is shown below. Note the structure of the returned object.

DateInterval Object
(
    [y] => 0
    [m] => 7
    [d] => 23
    [h] => 0
    [i] => 0
    [s] => 0
    [weekday] => 0
    [weekday_behavior] => 0
    [first_last_day_of] => 0
    [invert] => 0
    [days] => 238
    [special_type] => 0
    [special_amount] => 0
    [have_weekday_relative] => 0
    [have_special_relative] => 0
)

n/a