Php - 比较两个未来日期与当前日期的距离
Php - compare two future dates distance from current date
我正在尝试根据最接近现在的日期更改 $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');
}
使用getTimestamp
方法。
$interval1 = $wednesday->getTimestamp() - $currentTime->getTimestamp();
$interval2 = $saturday->getTimestamp() - $currentTime->getTimestamp();
在比较它们之前,您应该将间隔添加到 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;
我正在尝试根据最接近现在的日期更改 $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');
}
使用getTimestamp
方法。
$interval1 = $wednesday->getTimestamp() - $currentTime->getTimestamp();
$interval2 = $saturday->getTimestamp() - $currentTime->getTimestamp();
在比较它们之前,您应该将间隔添加到 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;