Skip to content

Commit 2a3785f

Browse files
authored
fix(plugin): timezone plugin prevent RangeError for invalid Day.js values (#3180) (#3181)
Add early-return guards in proto.tz and d.tz so that invalid dates return an invalid Day.js instance instead of throwing when Intl.DateTimeFormat.formatToParts receives an invalid Date. Regression introduced in 1.11.22 by e27ee80.
2 parents ae3a550 + dad46e6 commit 2a3785f

2 files changed

Lines changed: 18 additions & 0 deletions

File tree

src/plugin/timezone/index.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,7 @@ export default (o, c, d) => {
9393
const proto = c.prototype
9494

9595
proto.tz = function (timezone = defaultTimezone, keepLocalTime) {
96+
if (!this.isValid()) return this
9697
const oldOffset = this.utcOffset()
9798
const date = this.toDate()
9899
const target = date.toLocaleString('en-US', { timeZone: timezone })
@@ -140,6 +141,11 @@ export default (o, c, d) => {
140141
return d(input).tz(timezone)
141142
}
142143
const localTs = d.utc(input, parseFormat).valueOf()
144+
if (Number.isNaN(localTs)) {
145+
const ins = d(NaN)
146+
ins.$x.$timezone = timezone
147+
return ins
148+
}
143149
const [targetTs, targetOffset] = fixOffset(localTs, previousOffset, timezone)
144150
const ins = d(targetTs).utcOffset(targetOffset)
145151
ins.$x.$timezone = timezone

test/plugin/timezone.test.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -569,3 +569,15 @@ describe('DST edge cases vs moment', () => {
569569
})
570570
})
571571
})
572+
573+
it('does not throw for invalid Day.js values (regression #111.22)', () => {
574+
const invalid = dayjs('invalid')
575+
expect(invalid.isValid()).toBe(false)
576+
expect(() => invalid.tz('Europe/Skopje')).not.toThrow()
577+
expect(invalid.tz('Europe/Skopje').isValid()).toBe(false)
578+
})
579+
580+
it('does not throw for invalid string in d.tz()', () => {
581+
expect(() => dayjs.tz('invalid', 'Europe/Skopje')).not.toThrow()
582+
expect(dayjs.tz('invalid', 'Europe/Skopje').isValid()).toBe(false)
583+
})

0 commit comments

Comments
 (0)