Get time difference between two times in PHP using DateTime class

 Today in this post, we are going to see how to calculate and then get the time difference between two times in PHP.

You may notice on social media network like Facebook shows a post published “1 hour ago” or “2 minutes ago” or something like that. In that case, also, it is actually calculating the time difference. now I am going to see the easiest way of getting the time difference in PHP.

Let’s follow me…

Getting the difference between two times is a quite easy task. PHP already has the in-built DateTime class that can do it.

Below is an example where we have taken two date time string and showing it:

$time1 = new DateTime('2017-01-23 18:16:25');
$time2 = new DateTime('2019-01-23 11:36:28');
$timediff = $time1->diff($time2);
echo $timediff->format('%y year %m month %d days %h hour %i minute %s second')."<br/>";

The above PHP code will print the result that we can see below:

1 year 11 month 30 days 17 hour 20 minute 3 second

You can also print second, minutes, hours, day, month and year separately just by calling like methods from the DateTime class:

echo $timediff->s."<br/>";
echo $timediff->i."<br/>";
echo $timediff->h."<br/>";
echo $timediff->d."<br/>";
echo $timediff->m."<br/>";
echo $timediff->y."<br/>";

 

Continue reading Get time difference between two times in PHP using DateTime class