Php 为什么datetime->;天总是返回一个正数

Php 为什么datetime->;天总是返回一个正数,php,datetime,Php,Datetime,为什么这两个函数都返回正4? 如果日期在过去,如何返回负数?您可以使用 return$interval->format(“%r%a”) 如果需要,转换为int: return(int)$interval->format(“%r%a”)以下是您的答案: // Difference from a date in the future: $a = new DateTime('2000-01-01'); $b = new DateTime('2000-01-05'); $interval = $b-&g

为什么这两个函数都返回正4? 如果日期在过去,如何返回负数?

您可以使用

return$interval->format(“%r%a”)

如果需要,转换为int:

return(int)$interval->format(“%r%a”)

以下是您的答案:

// Difference from a date in the future:
$a = new DateTime('2000-01-01');
$b = new DateTime('2000-01-05');
$interval = $b->diff($a);
return $interval->days;             // Returns 4


// Difference from a date in the past:
$a = new DateTime('2000-01-01');
$b = new DateTime('1999-12-28');
$interval = $a->diff($b);           // Arguments swapped
return $interval->days;             // Returns 4

您可以像这样使用时间戳

$today = new DateTime();
$date = new DateTime('2013-03-10');
$interval = $today->diff($date);
echo $interval->format("%r%a");


$diff将返回负值或正值。

对两个DateTime对象进行差分时,以下规则适用:

<?php 
    $date1 = '2015-01-02';
    $date2 = '2015-01-05';
    $diff = strtotime($date1, 'Y-m-d') - strtotime($date2, 'Y-m-d'); 
?>
例如:

$objA->diff($objB) == $objB - $objA

如果日期已过,则将反转为1。
如果日期在将来,则反转为0

$todayDateObj = new \DateTime('2016/5/26');
$foundedDateObj = new \DateTime('1773/7/4');

$interval = $todayDateObj->diff($foundedDateObj);
echo $interval->format('%r%a') . "\n\n";
// -88714

$interval2 = $foundedDateObj->diff($todayDateObj);
echo $interval2->format('%r%a');
// 88714

Diff
的返回值是一个
DateInterval
对象。您是如何输出它的?抱歉,在我的代码中键入,现在更新
DateInterval
对象具有
invert
属性,指定它们是正的还是负的:不清楚$objA->diff($objB)==$objB-$objA。我将添加一个包含详细信息的新答案。此答案不完整/令人困惑:
如果日期在过去…
哪个日期?你比较了两次约会;)要回答这个问题(“为什么datetime->days总是返回一个正数?”):如果您期望一个负的返回值,则用$interval->invert=1表示
$invert    = $interval->invert;