How do I compare two DateTime objects in PHP 5.2.8

2019-01-01 08:32发布

This seems like something that should be pretty straight forward, but I have been stuck page faulting this problem for a while now, so here goes.

Having a look on the PHP documentation , the following two methods of the DateTime object would both seem to solve my problem:

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:

  • How do I compare two DateTime objects?
  • Where can I find the doco for previous PHP versions? Specifically version 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.

EDIT: 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 :).

I look forward to my embarrassment at the simplicity of your solution.

EDIT: And sure enough, embarrassment ensues ...

标签: php datetime
7条回答
孤独总比滥情好
2楼-- · 2019-01-01 09:14

This may help you.

$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";
}
查看更多
登录 后发表回答