Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose converting stored UTC dates to local time?

I'm wondering if this is normal, or if I'm missing something in the schema setup or query process:

My app, and mongoose, is correctly storing a date as UTC in mongodb. This is confirmed by viewing the documents via the mongo shell. When I retrieve the documents from mongodb via mongoose the date is now local time.

Is there a way to have mongoose keep the date as UTC when queried?

like image 489
DM. Avatar asked Jul 11 '13 14:07

DM.


2 Answers

Mongoose and node.js aren't doing anything to your dates, it's simply that the JavaScript Date type produces a local time string when you call toString() on it even though it actually contains the time in UTC.

Explicitly call toUTCString() on your Date object if you want a UTC time string.

like image 144
JohnnyHK Avatar answered Nov 03 '22 08:11

JohnnyHK


The timestamps are stored timezone agnostically, as a unix timestamp. This timestamp will work across timezones, and node interprets it using your current timezone. You can retrieve the UTC value from the date object using the getUTC* methods such as get getUTCHours()

like image 26
WouterH Avatar answered Nov 03 '22 10:11

WouterH