How to get UTC Date object in NodeJS?
36,560
Just use new Date(new Date().toUTCString())
After converting to UTC, we have to again convert it into Date object if we need a Date Object.
Related videos on Youtube
Author by
Nimish David Mathew
Updated on October 17, 2021Comments
-
Nimish David Mathew over 2 years
I want to get the Current Date object in UTC. I tried using
new Date()
,Date.now()
etc. But they return the local time. How do I get the UTC date object?I want the Date object, not string representation.
-
bugs about 6 years
-
Enric A. about 6 yearsI'd suggest storing the unix timestamp instead to avoid timezone hell
-
Luis Roberto almost 4 yearsnew Date() is just showing you a representation of the Time in your local timezone, internally it already contains the correct UTC value. I agree with the previous answer, just use Unix timestamp.
-
-
Enric A. about 6 yearsSorry I don't understand, you want to store the whole Date instance to mongoDB? If it's this, It doesn't make sense to me, just store a timestamp
-
Enric A. about 6 yearsThat's why I was suggesting storing a timestamp which is time zone agnostic and then convert it in code. The other way is always tricking and confusing
-
Luis Roberto almost 4 yearsThere is no difference between: new Date(new Date().toUTCString()) VS new Date() The "Date class" only gives you the illusion to have a different dates, but internally it's already a UTC value. Remember Date is only a representation of the Time. - Time is a milliseconds counter since 1970-01-01 00:00:00 - Date is a formatted representation only
-
baselsoftwaredev almost 3 yearsI have run this on my chrome console. it returned BST instead of UTC. Are we sure this is correct?
-
Kat Lim Ruiz over 2 yearsI used to believe this worked, but I dont think it does. Date is always local and UTC (you can get the individual values). Definitely the interface is rather poor. OTOH, if you run this in PAAS cloud (e.g Azure), this will always generate in UTC (servers are always set in UTC).