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.

Share:
36,560

Related videos on Youtube

Nimish David Mathew
Author by

Nimish David Mathew

Updated on October 17, 2021

Comments

  • Nimish David Mathew
    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
      bugs about 6 years
    • Enric A.
      Enric A. about 6 years
      I'd suggest storing the unix timestamp instead to avoid timezone hell
    • Luis Roberto
      Luis Roberto almost 4 years
      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.
  • Enric A.
    Enric A. about 6 years
    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.
    Enric A. about 6 years
    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
  • Luis Roberto
    Luis Roberto almost 4 years
    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
  • baselsoftwaredev
    baselsoftwaredev almost 3 years
    I have run this on my chrome console. it returned BST instead of UTC. Are we sure this is correct?
  • Kat Lim Ruiz
    Kat Lim Ruiz over 2 years
    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).