moment-timezone
moment-timezone copied to clipboard
Bug when parsing unix timestamp and using default time zone
As reported in moment/moment#3158 there is an issue where parsing an 'X' token will not work correctly with a default timezone.
moment.tz.setDefault("America/Chicago");
moment("1461906597", "X").isValid(); // false
This is an issue with the way updateOffset handles default time zones.
if (mom._z === undefined) {
if (zone && needsOffset(mom) && !mom._isUTC) {
mom._d = moment.utc(mom._a)._d;
mom.utc().add(zone.parse(mom), 'minutes');
}
mom._z = zone;
}
This bit of code will attempt to take the initial _a array from the moment config, and use it to construct a new UTC moment. With a timestamp, _a is an array with a bunch of undefined values, ergo this doesn't work.
I added a unit test for this to my fork of the repo: https://github.com/westy92/moment-timezone/commit/dde70303f5e148362090bb508918cb40a46d8bca.
Sorry, is there a solution for this issue at the moment (besides of the unit test added)?
Or, is there any other way to apply kind of "default" timezone to all subsequent moment().format() calls?
The workaround for now is to pass the timestamp as a number instead of a string.
moment.unix(1461906597) // seconds
moment(1461906597123) // milliseconds
If you have a string, then use + or parseInt to convert to number.
Thank you! Will it apply my default timezone, or just help to avoid errors?
It's a better form to use anyway, and yes - it will work with the default time zone. The bug is only that the default timezone isn't working with x or X string formats.