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/>";

 

Also, read:

Get time difference with current time

Now if we want to get the time difference between current time and a previous time, then we just have to put the current DateTime object “new DateTime()” just like below:

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

The output will be something like you can see below depending upon the current time:

1 year 0 month 12 days 23 hour 28 minute 22 second

 

So we have successfully calculated the difference between two times or dates. I hope you have understood.

Leave a Reply

Your email address will not be published. Required fields are marked *