26

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.

3
  • 1
    developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Apr 4, 2018 at 8:35
  • 2
    I'd suggest storing the unix timestamp instead to avoid timezone hell Commented Apr 4, 2018 at 8:37
  • new 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. Commented May 20, 2020 at 23:22

1 Answer 1

54

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.

Sign up to request clarification or add additional context in comments.

7 Comments

Sorry 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
That'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
There 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
I have run this on my chrome console. it returned BST instead of UTC. Are we sure this is correct?
I can also confirm that this method doesn't appear to work. When ran in the Firefox console, it returns the local timezone, not UTC!
I 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).
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.