Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting a date in mongodb

Tags:

php

mongodb

I want to insert a date into a collection. I use the class MongoDate to create the date object:

$today = new MongoDate(strtotime(date('Y-m-d 00:00:00')));

The problem is that once it is in my collection the date is 2 hours earlier.

For instance, $today here should be 2013-05-28 00:00:00 but once in the database it is 2013-05-27 22:00:00.

I can't resolve this problem by adding 2 hours manually to the timestamp because I use the date in queries.

The local time of the server where Mongo is running is set to the correct time of my country.

like image 539
Marc Dupuis Avatar asked May 28 '13 12:05

Marc Dupuis


People also ask

How is date stored in MongoDB?

The DATE type in MongoDB can store date and time values as a combined unit. The BSON Date type is a signed 64-bit integer representing the number of milliseconds since the Unix epoch (Jan 1, 1970).

How manually insert data in MongoDB?

The insert() Method To insert data into MongoDB collection, you need to use MongoDB's insert() or save() method.

What is MongoDB date format?

MongoDB date format yyyy-mm-dd.


3 Answers

That works in the new php version of mongodb:

new MongoDB\BSON\UTCDateTime((new DateTime($today))->getTimestamp()*1000)
like image 158
karrtojal Avatar answered Sep 19 '22 19:09

karrtojal


$dt = new DateTime(date('Y-m-d'), new DateTimeZone('UTC'));
$ts = $dt->getTimestamp();
$today = new MongoDate($ts);

This is working.

like image 22
Marc Dupuis Avatar answered Sep 18 '22 19:09

Marc Dupuis


Remove old document and insert

        $bill = array(  
                "_id" => 1, 
                "name" => "A", 
                "lastModified" => new MongoDate()
            );

        $collection->insert($bill);
like image 29
Gennady Kozlov Avatar answered Sep 20 '22 19:09

Gennady Kozlov