如何比较 PHP 5.2.8 中的两个 DateTime 对象? [英] How do I compare two DateTime objects in PHP 5.2.8?
问题描述
查看 PHP 文档,DateTime
对象的以下两种方法似乎都可以解决我的问题:
Having a look on the PHP documentation, the following two methods of the DateTime
object would both seem to solve my problem:
- DateTime::diff :获取差异并将其用于确定哪个更古老.
- DateTime::getTimestamp :获取 UNIX 时间戳并比较它们.
- DateTime::diff : Get the difference and use that to determine which is more ancient.
- DateTime::getTimestamp : Get the UNIX timestampt and compare those.
这两种方法都在 doco 中标记为在版本 >= 5.3 中可用(并且,不令人惊讶的是,如果我尝试调用它们,我会发现它们不存在).我找不到 5.2.8 的任何特定文档,所以我不确定我的版本中是否有等效的方法.我有 谷歌搜索这个问题并找到了一系列不拘一格的解决方案,但没有一个能满足我非常简单的要求:
Both these methods are marked in the doco as being available in version >= 5.3 (and, not surprisingly, if I try to call them I find they don't exist). I can't find any specific documentation for 5.2.8 so I am not sure if there are equivalent methods in my version. I have Googled the problem and found an eclectic range of solutions, none of which answer my very simple requirements:
- 如何比较两个 DateTime 对象?
- 在哪里可以找到以前 PHP 版本的 doco?特别是 5.2.8 版?
对于某些上下文,我有以下代码:
For some context, I have the following code:
$st_dt = new DateTime(verifyParam ('start_date'));
$end_dt = new DateTime(verifyParam ('end_date'));
// is the end date more ancient than the start date?
if ($end_dt < $start_dt)
显然这个人没有比较运算符.
Apparently there is no comparison operator on this guy.
显然我的假设是完全错误的(感谢 Milen 如此有效地说明了这一点).有一个比较运算符,它工作得很好,谢谢.有时我真的很想念一个编译器.错误在上面的代码中,我相信你会发现它比我做的要快得多:)
Apparently my assumptions were completely false (thanks Milen for illustrating this so effectively). There is a comparison operator and it works just fine thanks. Sometimes I really miss a compiler. The bug is in the code above, I am sure you will find it much faster than I did :).
推荐答案
以下似乎证实了 DateTime 类存在比较运算符:
The following seems to confirm that there are comparison operators for the DateTime class:
dev:~# php
<?php
date_default_timezone_set('Europe/London');
$d1 = new DateTime('2008-08-03 14:52:10');
$d2 = new DateTime('2008-01-03 11:11:10');
var_dump($d1 == $d2);
var_dump($d1 > $d2);
var_dump($d1 < $d2);
?>
bool(false)
bool(true)
bool(false)
dev:~# php -v
PHP 5.2.6-1+lenny3 with Suhosin-Patch 0.9.6.2 (cli) (built: Apr 26 2009 20:09:03)
Copyright (c) 1997-2008 The PHP Group
Zend Engine v2.2.0, Copyright (c) 1998-2008 Zend Technologies
dev:~#
这篇关于如何比较 PHP 5.2.8 中的两个 DateTime 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!