Jessie Emerson Jessie Emerson - 1 year ago 277
Node.js Question

datetime UTC conversion in mongodb

I do

new Date()
then save it into mongodb, the date became UTC format?

The datetime I inserted into mongodb when pull back is not the same, what should I do to solve this? Like I create a document on 1/12/2016, and I select range from 1/12/2016, the record is not there. Strange.

Answer Source

As the documentation says :

The mongo shell wraps the Date object with the ISODate helper. The ISODate is in UTC.

So my best guess is that your new Date() is not in UTC.

Math.floor((new Date()).getTime() / 1000)

as seen here: How do I get a UTC Timestamp in JavaScript?

However, Mongo is smart enough to sort this all out for you, so new Date() should be enough.

To query a Date in mongo, you can also use pure Date Objects, without the need to convert them to ISOString.

Keep everything as Date Objects, and it'll work as you intend it to!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download