我怎么知道date_diff的持续时间是多少?

时间:2015-12-31 14:53:35

标签: php datetime datediff

我有以下代码:

$sStart = date('Y-m-d H:i:s', strtotime($row['sStart']));
$sEnd   = date('Y-m-d H:i:s', strtotime($row['sEnd']));

$sStartDate = new DateTime($sStart);
$sEndDate   = new DateTime($sEnd);

$diff = date_diff($sStartDate, $sEndDate, true);

$dur = $diff->format('%h:%i');
来自MySQL数据库的

$row['sStart']$row['sEnd']datetime

如何判断$diff是否超过24小时?

2 个答案:

答案 0 :(得分:3)

$diff的类型为DateInterval

我认为这会给你使用date_diff结果的小时数:

$hours = ($diff->days * 24) + $diff->h;

if ($hours > 24) {
    // etc ..
}

答案 1 :(得分:1)

由于24小时为1天,您可以使用%a修饰符进行DateInterval::format调用,以计算间隔跨越的天数:

$sStartDate = DateTime::createFromFormat('Y-m-d H:i:s', '2013-05-13 21:56:00');
$sEndDate   = DateTime::createFromFormat('Y-m-d H:i:s', '2013-05-14 21:56:01');

$diff = date_diff($sStartDate, $sEndDate, true);

$days = $diff->format('%a');
if (1 <= $days) {
    echo '24 hours or more.';
} else {
    echo 'less than 24 hours.';
}

See it live.