如何在 PHP 中以小时分秒格式获取 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);
编辑
我在假设时差小于一天时犯了一个错误,所以如果时差大于一天,你只会看到小时:分钟:秒,这可能不是你想要的(如果忽略这个)
所以我现在会
$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://php.net/manual/en/function.date-diff.php
- 将这些字符串格式化为日期
- 将这些日期转换为毫秒
- 做日期 - 星日期
- 根据结果计算 h:mm:ss。
在这里看到它的工作: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