1

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.

Jessie Emerson
  • 743
  • 4
  • 12
  • 25

2 Answers2

0

The default timezone for node.js new Date() object is UTC (aka GMT).

You should leave it this way and just convert it on your front end. Javascript in the browser can convert the UTC timestamp to the browsers local timezone automatically.

new Date(Date.UTC(saved-timezone))

How do you create a JavaScript Date object with a set timezone without using a string representation

Community
  • 1
  • 1
Porlune
  • 740
  • 6
  • 16
0

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!

Community
  • 1
  • 1
xShirase
  • 11,975
  • 4
  • 53
  • 85