kylex
kylex

Reputation: 14406

Storing and retrieving dates in Mongodb 3.2 with PHPLIB

Using Mongo and PHP how does one store a datetime type, and then retrieve by date?

This is what I have for inserting, but it stores the date as a string:

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

How should I be sending the date to Mongo to store as a datetime type so I can do the proper finds?

Upvotes: 1

Views: 447

Answers (1)

Crouching Kitten
Crouching Kitten

Reputation: 1185

Put an instance of this class into the array: http://php.net/manual/en/class.mongodb-bson-utcdatetime.php

You need to use the BSON objects in the PHP arrays: http://php.net/manual/en/book.bson.php

Those get serialized properly before passed to Mongo.

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

$collection->insert($test);

The time() is multiplied by 1000, because the constructor wants the milliseconds elapsed since the unix epoch, and time() returns the seconds elapsed since the unix epoch. See: http://php.net/manual/en/mongodb-bson-utcdatetime.construct.php

UPDATE: To retrive the date/time in ISO format, just convert the UTCDateTime object fist to DateTime:

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

Upvotes: 2

Related Questions