Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get total time difference between two dates using php [duplicate]

Tags:

php

Possible Duplicate:
How to calculate the difference between two dates using PHP?

Here i mention two times with its date

2008-12-13 10:42:00

2010-10-20 08:10:00

I want to get total time difference in (h:m:s) format

like image 594
meginjoy Avatar asked May 22 '12 06:05

meginjoy


People also ask

How can I get the difference between two timestamps in PHP?

To calculate the difference between two dates in PHP, call date_diff() date/time function, and pass the two dates as argument to it. date_diff() function returns a DateInterval object, or FALSE if calculating the difference is not successful.

How can I calculate total hours in PHP?

There are two ways to calculate the total time from the array. Using strtotime() function: The strtotime() function is used to convert string into the time format. This functions returns the time in h:m:s format. Example 1: This example reads the values from the array and converts it into the time format.


2 Answers

If you are using or able to use PHP 5.3.x or later, you can use its DateTime object functionality:

$date_a = new DateTime('2010-10-20 08:10:00');
$date_b = new DateTime('2008-12-13 10:42:00');

$interval = date_diff($date_a,$date_b);

echo $interval->format('%h:%i:%s');

You can play with the format in a variety of ways, and once you have dates in DateTime objects, you can take advantage of a lot of different functionality, for example comparison via normal operators. See the manual for more: http://us3.php.net/manual/en/datetime.diff.php

like image 196
futureal Avatar answered Sep 21 '22 18:09

futureal


You can use the the strtotime function to turn the time to integers and subtract them.

$time1 = strtotime("2008-12-13 10:42:00");
$time2 = strtotime("2010-10-20 08:10:00");

$diff = $time2-$time1;
// the difference in int. then you can divide by 60,60,24 and 
// so on to get the h:m:s out of it
like image 31
Ibu Avatar answered Sep 19 '22 18:09

Ibu