25

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.

Nimish David Mathew
  • 2,958
  • 6
  • 29
  • 45
  • 1
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/UTC – bugs Apr 04 '18 at 08:35
  • 2
    I'd suggest storing the unix timestamp instead to avoid timezone hell – Enric A. Apr 04 '18 at 08: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. – Luis Roberto May 20 '20 at 23:22

1 Answers1

52

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.

Naimish Kher
  • 284
  • 1
  • 9
Enric A.
  • 893
  • 10
  • 18
  • 1
    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 – Enric A. Apr 04 '18 at 08:44
  • 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 – Enric A. Apr 04 '18 at 17:27
  • 8
    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 – Luis Roberto May 20 '20 at 23:25
  • 3
    I have run this on my chrome console. it returned BST instead of UTC. Are we sure this is correct? – baselsoftwaredev Jul 19 '21 at 09:02
  • 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). – Kat Lim Ruiz Dec 03 '21 at 21:55