moment / moment-timezone

Timezone support for moment.js
momentjs.com/timezone
MIT License
3.82k stars 835 forks source link

moment().valueOf returns a value even though it's invalid #1075

Closed tmkx closed 8 months ago

tmkx commented 11 months ago

Environment

moment.tz.setDefault();
t.ok(
  Number.isNaN(moment("2023/10/06", ["H", "HH", "HH:mm"], true).valueOf()),
);

moment.tz.setDefault('America/New_York');
// not expected
t.ok(
  Number.isNaN(moment("2023/10/06", ["H", "HH", "HH:mm"], true).valueOf()),
);

Issue description

when defaultZone is specified, valueOf will return a value even though it's invalid.

it seems to be caused by: https://github.com/moment/moment-timezone/blob/dffed7a8a9936e5be023ca76d389c258f1746dcd/moment-timezone.js#L643-L646

a fix that works:

- if (zone && needsOffset(mom) && !mom._isUTC) { 
+ if (zone && needsOffset(mom) && !mom._isUTC && mom.isValid()) { 
    mom._d = moment.utc(mom._a)._d;
    mom.utc().add(zone.parse(mom), 'minutes');
  }
sslincoco commented 11 months ago

您的邮件已收到,我会尽快给您回复。

gilmoreorless commented 8 months ago

Thanks for the detailed report. I've merged #1082 which contains the fix, and added your example as a test case in ece926a.