new Date() in wrong time zone

23,435

Using moment.js is the easiest way to accomplish what you are asking.

moment().format() // "2017-01-11T13:56:15-05:00"

The output is a string in ISO-8601 format, with time zone offset in effect in your local time zone.

You could do this yourself with a lot of code that reads the various properties of the Date object, building a string from those values. But it is not built-in to the Date object in this way.

Also, note any time you try to adjust a Date object by a time zone offset, you are simply picking a different point in time. You're not actually changing the behavior of the time zone being used by the Date object.

Share:
23,435
Ekom
Author by

Ekom

Updated on July 09, 2022

Comments

  • Ekom
    Ekom almost 2 years

    At the time of this post my current time is 2017-01-10T19:23:00.000Z but new Date() gives me 2017-01-11T00:23:19.521Z 5 hours ahead of my current timezone. This affects the way my data is stored in my MongoDB. I know I can set the time to 5 hours ago using

    var datetime    = new Date();
     datetime.setHours(datetime.getHours()-5); 
    

    But I will prefer a better way to do this. I tried using this. I still got the same time. In other parts of my code I get Tue Jan 10 2017 19:54:30 GMT-0500 (EST) different from the initial time. I will be happy if someone can point out what's wrong here.

  • Ekom
    Ekom over 7 years
    Thanks Matt. I think I will use moment.js.
  • m4heshd
    m4heshd about 6 years
    moment is the way to go.
  • Don Diego
    Don Diego about 3 years
    sadly this does not help if i need to create a date inputting day,month,year,hour, minute