php 为什么 datetime->days 总是返回一个正数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15421132/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why does datetime->days always returns a positive number
提问by JonoB
// 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
Why do both of these functions return positive 4? How do I return a negative number if a date is in the past?
为什么这两个函数都返回正数 4?如果日期在过去,如何返回负数?
回答by lafor
You could use DateInterval::format.
你可以使用DateInterval::format.
return $interval->format("%r%a");
return $interval->format("%r%a");
Cast to int if needed:
如果需要,转换为 int:
return (int)$interval->format("%r%a");
return (int)$interval->format("%r%a");
回答by Gurudutt Sharma
If Date is in past then invert will 1.
If Date is in future then invert will 0.
如果日期在过去,则反转为 1。
如果日期在未来,则反转为 0。
$invert = $interval->invert;
回答by Mehdi Karamosly
Here is your answer:
这是你的答案:
$today = new DateTime();
$date = new DateTime('2013-03-10');
$interval = $today->diff($date);
echo $interval->format("%r%a");
回答by Jay Sheth
When you are diffing two DateTime objects, the following rule applies:
当您比较两个 DateTime 对象时,以下规则适用:
$objA->diff($objB) == $objB - $objA
As an example:
举个例子:
$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
回答by yussan
you can use timestamp like this.
你可以像这样使用时间戳。
<?php
$date1 = '2015-01-02';
$date2 = '2015-01-05';
$diff = strtotime($date1, 'Y-m-d') - strtotime($date2, 'Y-m-d');
?>
$diff will return negative or positive.
$diff 将返回负数或正数。

