Php - 比较当前日期的两个未来日期距离

时间:2016-12-08 18:09:55

标签: php date time intervals

我试图根据最接近的日期更改$showThis。我如何比较时差?目前$interval1 > $interval2不起作用。我知道差异正在计算中,但我不确定如何比较两者。

$currentTime = new DateTime("now");
$wednesday = new DateTime('wednesday 10:59pm');
$saturday = new DateTime('saturday 10:59pm');
$interval1 = $currentTime->diff($wednesday);
$interval2 = $currentTime->diff($saturday);

if($interval1 > $interval2){
    $showThis = $saturday->format('D m/d/Y h:i A');
}
if($interval1 < $interval2){
    $showThis = $wednesday->format('D m/d/Y h:i A');
}

2 个答案:

答案 0 :(得分:1)

使用getTimestamp方法。

$interval1 = $wednesday->getTimestamp() - $currentTime->getTimestamp();
$interval2 = $saturday->getTimestamp() - $currentTime->getTimestamp();

答案 1 :(得分:0)

您应该在将比较之前将其添加到0日期,将间隔转换为秒:

$currentTime = new DateTime("now");
$wednesday = new DateTime('wednesday 10:59pm');
$saturday = new DateTime('saturday 10:59pm');

$interval1 = $currentTime->diff($wednesday);
$interval2 = $currentTime->diff($saturday);

$seconds1 = date_create('@0')->add($interval1)->getTimestamp();
$seconds2 = date_create('@0')->add($interval2)->getTimestamp();

if ($seconds1 > $seconds2){
    $showThis = $saturday->format('D m/d/Y h:i A');
}
else {
    $showThis = $wednesday->format('D m/d/Y h:i A');
}

echo $showThis;
相关问题