orszaczky
orszaczky

Reputation: 15605

Add new timezone to moment.js timezone

I have to add "Asia/Bangkok" (ICT) to moment.js, as it doesn't seem to support it by default.

After loading moment.js and moment-timezone.js I tried defining this specific timezone following this example:

moment.tz.add({
    "zones": {
        "Asia/Bangkok": [
            "6:42:4 - LMT 1880 6:42:4",
            "6:42:4 - BMT 1920_3 6:42:4",
            "7 - ICT"
        ],
    }
});

var currentTimeString = moment().tz('Asia/Bangkok').format('DD MMM YYYY, HH:mm:ss');

However, I keep getting the error:

"Moment Timezone has no data for Asia/Bangkok. See http://momentjs.com/timezone/docs/#/data-loading/."

Any ideas why?

Upvotes: 3

Views: 10974

Answers (1)

orszaczky
orszaczky

Reputation: 15605

I want to post my solution, for others struggling with the badly documented API of moment.js...

To create a time zone, you will have to create an unpacked timezone object:

var unpacked = {
    name    : 'Asia/Bangkok',
    abbrs   : ['ICT'],
    untils  : [null],
    offsets : [-420]
};

*Note that while ITC is UTC+7 the UTC offset in the array has to be the additive inverse (negative) of 7*60 = 420 for some reason.*

Before you can use it, you will also have to pack this object, and for that you need to include moment-timezone-utils.js

var packed = moment.tz.pack(unpacked);

It will spit out the packed timezone format partly encoded in Base 60: Asia/Bangkok|ICT|-70|0|

Now it can be added: moment.tz.add('Asia/Bangkok|ICT|-70|0|');

If you don't want to go through all this trouble, there is also a pre-packed file on GitHub, where you can pick the needed timezone.

Upvotes: 15

Related Questions