查看PHP文档,下面两个DateTime对象的方法似乎都可以解决我的问题:

DateTime::diff:获取差异并使用它来确定哪个更古老。 DateTime::getTimestamp:获取UNIX时间戳并进行比较。

这两个方法在doco中都被标记为在>= 5.3版本中可用(并且,毫不奇怪,如果我试图调用它们,我会发现它们不存在)。我找不到5.2.8的任何特定文档,所以我不确定在我的版本中是否有等效的方法。我在谷歌上搜索了这个问题,找到了一系列折衷的解决方案,但没有一个能满足我非常简单的要求:

如何比较两个DateTime对象? 我可以在哪里找到以前的PHP版本的doco ?特别是5.2.8版本?

对于某些上下文,我有以下代码:

$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) 

显然在这个东西上没有比较算子。

Edit

显然我的假设是完全错误的(感谢Milen如此有效地说明了这一点)。这里有一个比较运算符,它很好用,谢谢。有时候我真的错过了一个编译器。这个bug在上面的代码中,我相信你会比我更快地找到它:)。


当前回答

这可能对你有帮助。

$today = date("m-d-Y H:i:s");
$thisMonth =date("m");
$thisYear = date("y");
$expectedDate = ($thisMonth+1)."-08-$thisYear 23:58:00";


if (strtotime($expectedDate) > strtotime($today)) {
    echo "Expected date is greater then current date";
    return ;
} else
{
 echo "Expected date is lesser then current date";
}

其他回答

从PHP 7开始。X,您可以使用以下方法:

$aDate = new \DateTime('@'.(time()));
$bDate = new \DateTime('@'.(time() - 3600));

$aDate <=> $bDate; // => 1, `$aDate` is newer than `$bDate`

你也可以比较epoch秒:

$d1->format('U') < $d2->format('U')

来源:http://laughingmeme.org/2007/02/27/looking-at-php5s-datetime-and-datetimezone/ (关于DateTime的一篇很有趣的文章)

$elapsed = '2592000';
// Time in the past
$time_past = '2014-07-16 11:35:33';
$time_past = strtotime($time_past);

// Add a month to that time
$time_past = $time_past + $elapsed;

// Time NOW
$time_now = time();

// Check if its been a month since time past
if($time_past > $time_now){
    echo 'Hasnt been a month';    
}else{
    echo 'Been longer than a month';
}

这可能对你有帮助。

$today = date("m-d-Y H:i:s");
$thisMonth =date("m");
$thisYear = date("y");
$expectedDate = ($thisMonth+1)."-08-$thisYear 23:58:00";


if (strtotime($expectedDate) > strtotime($today)) {
    echo "Expected date is greater then current date";
    return ;
} else
{
 echo "Expected date is lesser then current date";
}

下面的代码似乎证实了DateTime类有比较操作符:

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:~#