16

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.

Mark Amery
  • 143,130
  • 81
  • 406
  • 459
Marc Dupuis
  • 523
  • 2
  • 5
  • 14
  • what wrong with saving a date as `new Date` object? it will include timezone data – Sagish May 28 '13 at 13:26
  • 1
    All dates in MongoDB are UTC, why cant you make your application timezone aware? – Sammaye May 28 '13 at 13:34
  • I use the dates as range in my queries with $gte and $lte operators. This is why I want to use the MongoDate format which allows comparison and is easily readable (timestamps are not). I need to find a way to insert a date independently of my timezone and the summer / winter hour change because this will cause problems. – Marc Dupuis May 28 '13 at 13:40
  • 2
    My PHP is quite rusty, but maybe this helps: http://stackoverflow.com/questions/3569014/php-strtotime-specify-timezone – Philipp May 28 '13 at 13:49
  • @Sagish: two reasons why it's _wrong_, so to speak. 1) if your code is that of an importer/updater tool, let's say from CSV datan, so, string, you want the insert/update method to implicitly cast the date to a MongoDB date data type. And 2) Date object would bear timezone data, but you only want to store dates all in UTC offset in MongoDB, and leave the renderer to present dates in local offset. – Fabien Haddadi Nov 18 '21 at 09:04

4 Answers4

21

That works in the new php version of mongodb:

new MongoDB\BSON\UTCDateTime((new DateTime($today))->getTimestamp()*1000)
karrtojal
  • 796
  • 7
  • 16
15
$dt = new DateTime(date('Y-m-d'), new DateTimeZone('UTC'));
$ts = $dt->getTimestamp();
$today = new MongoDate($ts);

This is working.

Marc Dupuis
  • 523
  • 2
  • 5
  • 14
2

Remove old document and insert

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

        $collection->insert($bill);
Gennady Kozlov
  • 1,011
  • 1
  • 11
  • 11
0

FYI: If you need date created for your object model.

$date_created = new \MongoDB\BSON\UTCDateTime(time()*1000);
Ego Slayer
  • 1,987
  • 2
  • 22
  • 17