miszczu
miszczu

Reputation: 1189

Compare DateTime objects in PHP

I have a question about comparing dates set like that $date=new DateTime($_GET['date']);.

I know there is $date1->diff($date2); but this returns difference only.

This works fine when I made some tests:

$query='';
while ($date1 < $date2) {
  $query='...'.$date->format("Y-m-d").'...;';
  $date1->modify("+1 days");
}
$db->query($query);

My question: is that the right way of comparing 2 date objects? When I test it, results were ok, but is it possible I could get an error when script check while condition?

Upvotes: 2

Views: 3116

Answers (1)

m4t1t0
m4t1t0

Reputation: 5731

Taken from PHP manual at: http://www.php.net/manual/en/class.datetime.php

Changelog:

Version: 5.2.2 Description: DateTime object comparison with the comparison operators changed to work as expected. Previously, all DateTime objects were considered equal (using ==).

So if you are using PHP 5.2.2 or superior, you must have no problems.

Upvotes: 3

Related Questions