How to use ISODate in PHP/Laravel

In MongoDB Date objects are stored as a signed 64-bit integer representing the number of milliseconds since the Unix epoch (Jan 1, 1970). Not all database operations and drivers support the full 64-bit range. You may safely work with dates with years within the inclusive range 0 through 9999.

ISODate is not supported by PHP/MongoDB driver rather it is available for MongoDB Shell. Hence date is saved as milliseconds internally in MongoDB, we need to query by milliseconds instead.
MongoDB PHP driver provides a UTCDateTime Class which takes milliseconds as a constructor argument and provides an ISODate equivalent.

So instead of writing

$start_date = strtotime("2018-11-21 13:00:00");
where created_at >= ISODate($start_date)

We need to use

where created_at >= new \MongoDB\BSON\UTCDateTime(($start_date * 1000)))

Hence time() function returns time in seconds we need to multiply it with 1000 to get miliseconds.

One thought on “How to use ISODate in PHP/Laravel

Leave a Reply

Your email address will not be published. Required fields are marked *