PHP - Compare two mongodates

2.6k views Asked by At

Can i compare 2 mongodates like below? In my testing it is working good. But mongodates are objects and will they work the same way in future as well?

$d1 = new MongoDate(1391671630);
$d2 = new MongoDate(1391671631);

echo ($d1 < $d2); //returns 1 which is correct. 
//and i tried all other comparisons (>, ==, >=, <=). Everything works good. 
3

There are 3 answers

5
Sammaye On

You will need to use the sec property of the MongoDate object:

$d1->sec < $d2->sec
1
Neil Lunn On

The drivers are maintained by staff at MongoDB, well most of them. So the majority of things listed as a base driver implementation are always going to be part of the specification anyhow.

Under the hood MongoDB actually stores the value as an epoch timestamp internally and the MongoDate class is making sure that this is passed in over the wire as the valid BSON type with the correct value. So it's in your advantage that you use a type recognized internally so the server side comparison of dates works as expected.

2
jmikola On

The MongoDate classes in the mongo driver have no special support for comparison operators. The behavior you're seeing is likely internal PHP behavior, where comparing two objects with <, <=, >, and >= operators examines the properties in order. It just so happens that MongoDate declares its $sec property before $usec, so this works out. I didn't find this behavior documented in the PHP manual, but it is discussed in this comment on the page where I'd expect to find it.

You may want to track PHP-226, as there are plans to add a helper method to return the float value of a MongoDate (akin to microtime(true)). As-is, the __toString() return value isn't very helpful, since microseconds appear before seconds.

I've also opened PHP-979 to track this as a feature request (overloading support for comparison operators).