Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

get difference in time in HH:MM format php

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...