Search code examples
phpmongodbisodate

Insert ISODate in Mongodb with milliseconds


I'm running PHP 7 with the php_mongodb-1.2.2-7.0-nts-vc14-x64 driver.

$ar = new \MongoDB\BSON\UTCDateTime(strtotime('2017-07-27 06:17:25.123000') * 1000);

Output of above statement is:

ISODate("2017-07-27T06:17:25.000+0000")

but I need milliseconds also like:

ISODate("2017-07-27T06:17:25.123+0000")

Since I'm so new I can't seem to figure out how to fix this.


Solution

  • strtotime do not support milliseconds.

    strtotime — Parse about any English textual datetime description into a Unix timesta

    So the strtotime('2017-07-27 06:17:25.123000') and strtotime('2017-07-27 06:17:25') will return the same result 1501136245

    You must use DateTime:

    <?php
    $date = DateTime::createFromFormat('Y-m-d H:i:s u', '2017-07-27 06:17:25 123000');
    $ar = new \MongoDB\BSON\UTCDateTime($date->format('U.u'));