PHP:Datetime :: Diff结果比较 [英] PHP: Datetime::Diff results comparison
问题描述
我正在尝试比较两个日期之间的差异,但是结果似乎是错误的,例如以下代码:
i was trying to compare the difference between 2 dates, but it seems the results are pretty wrong, for example this code:
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days')."<br />";
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-15');
$interval2 = $datetime1->diff($datetime2);
echo $interval2->format('%R%a days')."<br />";
if($interval == $interval2){ echo "true"; }else{echo "false"; }
返回true,但在上面您可以看到日期差异并不相同,实际上是回显打印+2和+4。对如何比较2个日期差有任何想法吗?
Returns true, but above you can see the date differences are not the same, in fact echo prints +2 and +4. Any idea in how to compare 2 date differences?
编辑:datetime :: diff返回dateinterval对象,实际上它没有实现比较运算符, https://bugs.php.net/bug.php?id=49914
我将使用dateinterval vars检查差异,谢谢答案
the datetime::diff returns a dateinterval object, in fact it doesn't implement comparison operators, https://bugs.php.net/bug.php?id=49914 I'll use dateinterval vars to check the difference, thanks for the answers
推荐答案
似乎DateInterval在内部没有实现比较功能。扩展允许为其预定义的类定义自定义比较规则。显然,可以归结为一个松散的比较,即对象是同一类。
It seems that DateInterval doesn't implement a comparison function internally. Extensions are allowed to define custom comparison rules for their predefined classes. Evidently it falls back to a loose comparison that the objects are of the same class.
此功能请求提供了一个补丁,用于在其中添加此功能,但似乎在任何时候都未将其添加到源代码中。
This feature request provides a patch to add this functionality in, but it doesn't seem to have made it into the source at any point.
要解决此问题,您可以自己比较对象的每个成员变量(年,月等),也可以将每个对象强制转换为数组:
To get around this issue, you can either compare each member variable of your objects yourself (years, months etc.) or you can cast each object to an array:
if ((array) $interval == (array) $interval2) {
echo 'true';
} else {
echo 'false';
}
这篇关于PHP:Datetime :: Diff结果比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!