moment-timezone icon indicating copy to clipboard operation
moment-timezone copied to clipboard

Bug when parsing unix timestamp and using default time zone

Open maggiepint opened this issue 9 years ago • 5 comments
trafficstars

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.

maggiepint avatar Apr 30 '16 01:04 maggiepint

I added a unit test for this to my fork of the repo: https://github.com/westy92/moment-timezone/commit/dde70303f5e148362090bb508918cb40a46d8bca.

westy92 avatar May 19 '16 23:05 westy92

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?

mityukov avatar Jul 24 '17 18:07 mityukov

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.

mattjohnsonpint avatar Jul 26 '17 19:07 mattjohnsonpint

Thank you! Will it apply my default timezone, or just help to avoid errors?

mityukov avatar Jul 27 '17 07:07 mityukov

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.

mattjohnsonpint avatar Jul 27 '17 22:07 mattjohnsonpint