Vadim Samokhin
Vadim Samokhin

Reputation: 3456

Php object-oriented-style date comparison

How do you prefer to compare dates when it comes to OOP? What do you think about:

$date1 = new Date();
...
$date2 = new Date();

if ($date1 > $date2) {
    ...
}

Please do not put in example anything like strtotime etc., only OOP.

Upvotes: 0

Views: 388

Answers (2)

Stefan Gehrig
Stefan Gehrig

Reputation: 83622

If Date should have been the internal DateTime class, your code is absolutely fine. But if Date is a custom class, the code will not work as expected. Unlike other programming languages PHP does not allow operator overloading which is required for your code to work. You'd need something that tells PHP how it should work with the comparison operators on instances of your class, because PHP cannot know how to compare $date1 and $date2 and determine which one is larger.

You could however define some comparison methods on your class...

$date1->isLargerThan($date2);

Upvotes: 0

mfonda
mfonda

Reputation: 7993

If you're using PHP DateTime objects, you can compare dates using the standard comparison operators. For more info and examples, see the DateTime::diff manual page.

Here is example #2 from the manual:

$date1 = new DateTime("now");
$date2 = new DateTime("tomorrow");

var_dump($date1 == $date2);
var_dump($date1 < $date2);
var_dump($date1 > $date2);

Upvotes: 3

Related Questions