如何在php中以hrs min sec格式获取start_date和end_date之间的持续时间?
$start_date=2012-03-23 11:58:14 and $end_date=2012-03-24 11:54:29
如何在php中以hrs min sec格式获取start_date和end_date之间的持续时间?
$start_date=2012-03-23 11:58:14 and $end_date=2012-03-24 11:54:29
使用DateTime
类:
$start_date = new DateTime('2012-03-23 11:58:14');
$end_date = new DateTime('2012-03-24 11:54:29');
$dd = date_diff($end_date, $start_date);
获取小时使用$dd->h
,分钟 - $dd->i
,秒 - $dd->s
。
echo "Hours = $dd->h, Minutes = $dd->i, Seconds = $dd->s";
我会
$start_time = strtotime($start_date);
$end_time = strtotime($end_date);
$difference = $end_time - $start_time;
echo date('H:i:s', $difference);
编辑
我在假设时差小于一天时犯了一个错误,所以如果时差大于一天,你只会看到 Hours:minuetes:seconds,这可能不是你想要的(如果它是忽略这个)
所以我现在会
$seconds = $difference % 60; //seconds
$difference = floor($difference / 60);
$min = $difference % 60; // min
$difference = floor($difference / 60);
$hours = $difference; //hours
echo "$hours : $min : $seconds";
抱歉更正
这个功能可以帮助你
function datediff($interval, $datefrom, $dateto, $using_timestamps = false) {
/*
$interval can be:
yyyy - Number of full years
q - Number of full quarters
m - Number of full months
y - Difference between day numbers
(eg 1st Jan 2004 is "1", the first day. 2nd Feb 2003 is "33". The datediff is "-32".)
d - Number of full days
w - Number of full weekdays
ww - Number of full weeks
h - Number of full hours
n - Number of full minutes
s - Number of full seconds (default)
*/
看到它在这里工作:http ://codepad.viper-7.com/FPuOks
$start_date="2012-03-22 11:58:14";
$end_date="2012-03-24 11:54:29";
$start_time = strtotime($start_date);
$end_time = strtotime($end_date);
$difference = $end_time - $start_time;
echo sprintf("%02d%s%02d%s%02d", floor($difference/3600), ':', ($difference/60)%60, ':', $difference%60); // outputs 47:56:15