【问题标题】:Storing and retrieving dates in Mongodb 3.2 with PHPLIB使用 PHPLIB 在 Mongodb 3.2 中存储和检索日期
【发布时间】:2017-01-07 21:51:48
【问题描述】:

使用Mongo和PHP如何存储日期时间类型,然后按日期检索?

这是我插入的内容,但它将日期存储为字符串:

$collection->insertOne(['date_created' => '2017-01-02 17:20:15']);

我应该如何将日期发送到 Mongo 以存储为日期时间类型,以便进行正确的查找?

【问题讨论】:

    标签: php mongodb phplib


    【解决方案1】:

    将这个类的一个实例放入数组中:http://php.net/manual/en/class.mongodb-bson-utcdatetime.php

    您需要在 PHP 数组中使用 BSON 对象:http://php.net/manual/en/book.bson.php

    那些在传递给 Mongo 之前会被正确序列化。

    $test = array(  
        "_id" => 123, 
        "name" => "This is an example", 
        "date_created" => new MongoDB\BSON\UTCDateTime(time() * 1000)
    );
    
    $collection->insert($test);
    

    time() 乘以 1000,因为构造函数需要自 unix 纪元以来经过的毫秒数,而 time() 返回自 unix 纪元以来经过的秒数。见:http://php.net/manual/en/mongodb-bson-utcdatetime.construct.php

    更新: 要检索 ISO 格式的日期/时间,只需将 UTCDateTime 对象拳头转换为 DateTime:

    $date_created = $test["date_created"];
    $iso_date = $date_created->toDateTime()->format("Y-m-d H:i:s");
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-18
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 2012-03-18
    • 2014-10-24
    • 2013-08-20
    相关资源
    最近更新 更多