Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

272
Views
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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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");
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!