ps0604
ps0604

Reputation: 1081

Moment.js uses a different time zone than the one defined in the system

I'm running Moment on a laptop with Windows 10 in EST, timezone UTC-05:00. I didn't define the daylight savings time in the laptop, but when I run the code below Moment converts the date to UTC-04:00. Why does Moment use a different timezone than the one defined in the laptop?

        var ts = "2019-04-01T18:22:57.813";
        var dateTime = moment(ts, 'YYYY-MM-DD HH:mm').toDate();
        console.log(dateTime);

Upvotes: 0

Views: 3118

Answers (2)

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241920

... Windows 10 in EST, timezone UTC-05:00. I didn't define the daylight savings time in the laptop...

From your explanation, I assume your time zone settings look like this:

time zone settings screenshot

The (UTC-05:00) Eastern Time (US & Canada) display name matches the Windows time zone ID of Eastern Standard Time, which corresponds to the IANA time zone ID of America/New_York. That time zone currently uses UTC-5 during standard time and UTC-4 during daylight time. It doesn't matter that it says "(UTC-05:00)" in the display name string, it still honors DST as applicable in that time zone.

The "Adjust for daylight saving time automatically" feature is normally turned on for time zones that have daylight saving time. Turning it off, as shown here, is generally not recommended. The problem is that some software will not evaluate that flag, and simply look at the time zone identifier. For web browsers, you'll find that Edge will honor this flag, but Chrome will not.

There's really no good reason to disable this. If you need a time zone that is UTC-5 without DST, such as (UTC-05:00) Bogota, Lima, Quito, Rio Branco, then simply choose that time zone.

And lastly, recognize that this has nothing to do with Moment.js. You will see the same behavior just with the JavaScript Date object. Since DST is in effect in US Eastern Time on April 1st, then you will see UTC-4 for that date.

On the other hand, if what you really wanted was to interpret the given date and time as being in UTC-5 regardless of the local computer settings, Moment can help you with that:

var m = moment.parseZone("2019-04-01T18:22:57.813-05:00");
m.format() //=> "2019-04-01T18:22:57-05:00"

Though if you do m.toDate(), then you'll get back a Date object, which is once again going to pick up the computer's local time zone. For this scenario, try to avoid Date objects if you can.

Upvotes: 2

CraftyMonkey
CraftyMonkey

Reputation: 415

By default moment.js use local time zone (node timezone): https://momentjscom.readthedocs.io/en/latest/moment-timezone/01-using-timezones/05-default-timezone/ And if unset, by default node.js use UTC timezone, check out: Where does Node.js get it's timezone and how can I set it globally?

Upvotes: 0

Related Questions