为什么datetime-> days总是返回一个正数

Jon*_*noB 45 php datetime

// 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
Run Code Online (Sandbox Code Playgroud)

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

laf*_*for 68

你可以用DateInterval::format.

return $interval->format("%r%a");

如果需要,转换为int:

return (int)$interval->format("%r%a");


Gur*_*rma 20

如果Date在过去,则反转将为1.
如果日期是将来,则反转将为0.

$invert    = $interval->invert; 
Run Code Online (Sandbox Code Playgroud)

  • 这个答案是不完整的/令人困惑的:“如果日期过去了……”哪个日期?您比较两个约会对象;) (3认同)

Meh*_*sly 8

这是你的答案:

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

在这里测试一下


Jay*_*eth 5

当您比较两个 DateTime 对象时,适用以下规则:

$objA->diff($objB) == $objB - $objA
Run Code Online (Sandbox Code Playgroud)

举个例子:

$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
Run Code Online (Sandbox Code Playgroud)