How to configure Time Zone in MongoDB


As you can configure the time zone for mongodb, when you insert an insert in mongo with new Date (), you register 5 additional hours. for example:


db.publication.insert ({_ id: 1, date: new Date ()});   WriteResult ({"nInserted": 1})   db.publication.findOne (_id: 1)   2016-10-19T14: 08: 22.156-0500 SyntaxError: Unexpected token:   db.publication.findOne ({_ id: 1})   {"_id": 1, "date": ISODate ("2016-10-19T19: 08: 14.027Z")}

I consider making a method to set this time to my local time, in this case -5 hours for Colombia, but if it is possible to make modification to the mongodb server I would prefer to do this, but I do not know if it can be done.

asked by Tavo Ruiz 19.10.2016 в 21:20

1 answer


MongoDB by default saves all dates in UTC. There is no way to save dates in a different time zone; however, you can use getTimezoneOffset() of Date to get the difference and manage the time zones from the application, like this:

var fecha = new Date(); { date: fecha,
                       offset: fecha.getTimezoneOffset() } );

This will save a document in MongoDB like the following:

{ "_id" : ObjectId("5807fc6fe820a6d1afe44fda"), "fecha" : ISODate("2016-10-19T23:05:55.336Z"), "offset" : 360 }

Now, since we have the offset, we can subtract it from the date to obtain the original date / time:

var documento = db.publication.findOne();
var fechaOriginal = new Date( documento.fecha.getTime() -  ( documento.offset * 60000 ) );

fechaOriginal will have the date from the time zone that the operation was performed.

answered by 20.10.2016 в 01:25