【问题标题】:Insert ISODate in Mongodb with milliseconds以毫秒为单位在 Mongodb 中插入 ISODate
【发布时间】:2017-07-27 11:58:57
【问题描述】:

我正在使用 php_mongodb-1.2.2-7.0-nts-vc14-x64 驱动程序运行 PHP 7。

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

上述语句的输出为:

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

但我也需要毫秒:

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

由于我是新手,我似乎无法弄清楚如何解决这个问题。

【问题讨论】:

    标签: php mongodb isodate


    【解决方案1】:

    strtotime 不支持毫秒。

    strtotime — 将任何英文文本日期时间描述解析为 Unix 时间戳

    所以strtotime('2017-07-27 06:17:25.123000')strtotime('2017-07-27 06:17:25') 将返回相同的结果1501136245

    您必须使用日期时间:

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

    【讨论】:

    • 那么毫秒用哪个函数?
    【解决方案2】:

    你可以这样做

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

    示例输出:

    MongoDB\BSON\UTCDateTime 对象 ( [毫秒] => 1610972571000 )

    上面的函数以毫秒为单位准备当前的 datetime 对象,准备插入 mongoDB。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-11
      • 2015-09-16
      • 2020-08-03
      • 1970-01-01
      • 2020-02-22
      • 2012-03-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多