Daniel Cheng
Daniel Cheng

Reputation: 870

Formatting time in user's timezone with moment.js

I am having some trouble with the combination on PhantomJS and Moment.js. I would like to format a unix timestamp e.g. 1399089600000 in user's timezone in PhantomJS. However, I see some weird behavior. My machine timezone is Asia/Hong_Kong (UTC+8).

Below are ran in PhantomJS with env var TZ=Asia/Hong_Kong

var moment = require('moment.js');
moment(1399089600000).utc().format('YYYY-MM-DD HH:mm:ss Z');
// "2014-05-03 04:00:00 +00:00" which is ok
moment(1399089600000).local().format('YYYY-MM-DD HH:mm:ss Z');
// "2014-05-04 05:00:00 +25:00" why +25?
moment(1399089600000).format('YYYY-MM-DD HH:mm:ss Z');
// "2014-05-04 05:00:00 +25:00" why +25?

When TZ=UTC

moment(1399089600000).utc().format('YYYY-MM-DD HH:mm:ss Z');
// "2014-05-03 04:00:00 +00:00" which is ok
moment(1399089600000).local().format('YYYY-MM-DD HH:mm:ss Z');
// "2014-05-04 04:00:00 +24:00" why +24?
moment(1399089600000).format('YYYY-MM-DD HH:mm:ss Z');
// "2014-05-04 04:00:00 +24:00" why +24?

When TZ is not set, things seem to be fine,

moment(1399089600000).utc().format('YYYY-MM-DD HH:mm:ss Z');
// "2014-05-03 04:00:00 +00:00" which is ok
moment(1399089600000).local().format('YYYY-MM-DD HH:mm:ss Z');
// "2014-05-03 12:00:00 +08:00" which is ok
moment(1399089600000).format('YYYY-MM-DD HH:mm:ss Z');
// "2014-05-03 12:00:00 +08:00" which is ok

PhantomJS 2.1.1 and Moment.js 2.17.1 are used.

Thanks.

Update

When TZ=Asia/Hong_Kong, moment(1399089600000).utcOffset() = 1500

When TZ=UTC, moment(1399089600000).utcOffset() = 1440

When TZ=, moment(1399089600000).utcOffset() = 480

Upvotes: 1

Views: 957

Answers (1)

Daniel Cheng
Daniel Cheng

Reputation: 870

Turns out PhantomJS does not play well with Windows when it comes to the TZ environment variable.

Taking momentjs out of the equation:

In a Windows machine:

When TZ=UTC, new Date().getTimezoneOffset() returns -1440 which is wrong.

But in a Linux machine (Ubuntu when I tested):

When TZ=UTC, new Date().getTimezoneOffset() returns 0 which is correct.

I tested other variations of TZ values on Linux and they are all correct.

Upvotes: 0

Related Questions