Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get difference in time in HH:MM format php

Tags:

php

time

datediff

how can i get this to output

HH:MM format?

 $to_time = strtotime("2008-12-13 10:42:00");  <--AM
 $from_time = strtotime("2008-12-14 8:21:00");  <-- PM
 $stat = round(abs($to_time - $from_time) / 60,2). "min";

what i got from this is 1299 mins

but i cant figure out how to make it output

21h:41m

like image 574
telexper Avatar asked Oct 21 '12 22:10

telexper


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 get different time in PHP?

Use date_diff() Function to Get Time Difference in Minutes in PHP. We will use the built-in function date_diff() to get time difference in minutes. For this, we need a start date and an end date. We will calculate their time difference in minutes using the date_diff() function.

How to print date in different format in PHP?

Change YYYY-MM-DD to DD-MM-YYYY In the below example, we have date 2019-09-15 in YYYY-MM-DD format, and we will convert this to 15-09-2019 in DD-MM-YYYY format. $orgDate = "2019-09-15"; $newDate = date("d-m-Y", strtotime($orgDate)); echo "New date format is: ".

How to set date time format in PHP?

Example. $date=date_create("2013-03-15"); echo date_format($date,"Y/m/d H:i:s");


2 Answers

Firstly, 8:21:00 will be interpreted as 8AM unless you specified otherwise using DateTime::createFromFormat().

To work out time differences, use DateTime::diff():

$to = new DateTime("2008-12-13 10:42:00");
$from = new DateTime("2008-12-14 8:21:00");

$stat = $to->diff($from); // DateInterval object

echo $stat->format('%Hh:%Im');

This will display the hour/minute difference between the two times, but only up to 24 hours.

If you need more than 24 hours, you should do the following:

$hours   = $stat->days * 24 + $stat->h;
$minutes = $stat->i;

printf('%02sh:%sm', $hours, $minutes);
like image 80
noetix Avatar answered Oct 03 '22 00:10

noetix


First of all you need to include AM and PM in your date strings, otherwise 2008-12-14 8:21:00 will be interpreted as 8:21 AM

Now the difference between two dates is 2019 that is 33h:19m, you cant' have t with standard date formats, since they support only 24h clock. You should keep $stat as integer, and display it with sprintf like like this:

echo sprintf('%02dh:%02dm', $stat/60, $stat%60);
like image 38
dev-null-dweller Avatar answered Oct 03 '22 01:10

dev-null-dweller