简体   繁体   中英

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.

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'));

You can do something like this

function mongo_current_datetime(){
    $date = new \MongoDB\BSON\UTCDateTime(strtotime('now') * 1000);
    return $date;
}

Example Output:

MongoDB\\BSON\\UTCDateTime Object ( [milliseconds] => 1610972571000 )

The function above prepares current datetime Object in milliseconds , ready to insert into mongoDB.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM