【问题标题】:Php - compare two future dates distance from current datePhp - 比较两个未来日期与当前日期的距离
【发布时间】:2016-12-08 18:09:54
【问题描述】:
我正在尝试根据最接近现在的日期更改$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');
}
【问题讨论】:
标签:
php
date
time
intervals
【解决方案1】:
使用getTimestamp 方法。
$interval1 = $wednesday->getTimestamp() - $currentTime->getTimestamp();
$interval2 = $saturday->getTimestamp() - $currentTime->getTimestamp();
【解决方案2】:
在比较它们之前,您应该通过将其添加到 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;