Repository navigation
fix(timezone): re-resolve the zone offset in calendar math across DST - #3363
dacheng-sa wants to merge 5 commits into
Conversation
Zoned instances kept a fixed UTC offset, so calendar arithmetic and keepLocalTime conversions went wrong across DST (iamkun#1271, iamkun#2609, mui/mui-x#10584): - add/subtract with day/week/month/year and setters now work on the zone's wall clock and re-resolve the offset with fixOffset. Exact units (h/m/s/ms) add elapsed time to the real instant. - tz(zone, true) and startOf/endOf resolve the offset at the target wall time instead of at the current instant. - Zoned instances are built from a host-local Date that already shows the zone's wall clock, so a host DST change no longer shifts the fields. - dayjs.tz(string, zone) resolves an ambiguous fall-back time to the earlier instant, like moment, instead of depending on today's date. Everything stays inside the timezone plugin; core and the utc plugin are unchanged, as discussed in iamkun#3169. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…les host
Adds moment-parity regression tests for add/subtract, setters,
startOf/endOf, keepLocalTime and ambiguous parses across DST, plus the
startOf('day') case reported on iamkun#3169. Runs the timezone plugin tests on an
America/Los_Angeles host too, which exposes the host-DST bug the other
hosts in the matrix miss.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Some tests use fixed UTC timestamps and assume a host at or ahead of UTC, so a few fail on a clean checkout west of UTC. Document this and suggest TZ=UTC npm test to match CI. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…t out of iamkun#3174 The comments blamed moment for wrong keepLocalTime and gap results, but that is moment-timezone 0.5.31 / moment 2.29.2 pinned in devDependencies; moment 2.31 agrees with these expectations. Also covers keepLocalTime into America/Guadeloupe on the EU spring-forward day (left out of iamkun#3174) and keepLocalTime at 03:00:01 on LA's spring-forward day. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
UnderHear
left a comment
There was a problem hiding this comment.
Please preserve invalid-date propagation before calling fixOffset in fromWallClock (lines 100–101). On head 164e3d4, the new startOf path passes NaN into this helper for dayjs.tz('invalid', 'Europe/Skopje').startOf('day'). The existing d.tz guard deliberately returns an invalid instance with $timezone, so this reaches fixOffset → tzOffset → Intl.DateTimeFormat.formatToParts(new Date(NaN)) and throws a RangeError. On dev, startOfWithoutTz.tz(...) instead reaches the invalid-instance early return in proto.tz, preserving an invalid result. endOf delegates to startOf and is affected too.
The same missing guard affects newly invalid results from a valid zoned instance, e.g. dayjs.tz('2024-01-15', 'Europe/Paris').add(NaN, 'day') or .set('date', NaN): the early this.isValid() checks pass, but the computed wall timestamp is invalid. Please return an invalid instance (preserving locale/timezone metadata) before the Intl lookup and add regression tests for these chains. The existing test at lines 580–583 only checks creation of an invalid zoned instance, not subsequent operations.
This is an AI-assisted static source review with OpenAI Codex, comparing the current PR, dev, and the existing invalid-input context in #1637. I have not executed these examples or the test suite.
| return fromWallClock(wall.valueOf(), timezone, this.utcOffset(), this.$L) | ||
| } | ||
| // elapsed time: add to the real instant (as UTC, so no host DST applies), then convert back | ||
| const instant = oldAdd.call(d.utc(this.valueOf()), number, units).valueOf() |
There was a problem hiding this comment.
This only works when quarterOfYear / duration are extended after timezone. If they are extended first (e.g. alphabetical order: duration, quarterOfYear, utc, timezone), p('quarter') and a Duration object are not in CALENDAR_UNITS, so they go down the elapsed path and the month/day math runs on a UTC instance. The wall clock then moves by the DST hour:
dayjs.extend(quarterOfYear); dayjs.extend(duration)
dayjs.extend(utc); dayjs.extend(timezone)
dayjs.tz('2021-01-15 12:00', 'America/New_York').add(1, 'quarter').format()
// 2021-04-15T13:00:00-04:00 (moment: 12:00-04:00)
dayjs.tz('2021-03-13 12:00', 'America/New_York').add(dayjs.duration(1, 'day')).format()
// 2021-03-14T13:00:00-04:00 (moment: 12:00-04:00)With the other order, both give 12:00 like moment. One fix: let those plugins split the value on this, so each piece comes back through this add (also needs Q in the constant import):
| const instant = oldAdd.call(d.utc(this.valueOf()), number, units).valueOf() | |
| // quarterOfYear / duration extended before timezone: let them split the value | |
| // into units on this instance, so each unit comes back through this add | |
| if (this.$utils().p(units) === Q || (d.isDuration && d.isDuration(number))) { | |
| return oldAdd.call(this, number, units) | |
| } | |
| if (CALENDAR_UNITS.indexOf(this.$utils().p(units)) > -1) { |
With that, both orders match moment for these cases, and the timezone, duration and quarterOfYear test files still pass (102 tests, TZ=UTC). subtract(duration) is already fine in both orders, since the duration plugin's own subtract calls this.add per unit.
There was a problem hiding this comment.
Good catch, thanks! Reproduced both of your examples. I went with your idea in 4f919e9, slightly widened, since objectSupport turned out to have the same problem: add({ days: 1 }) also landed at 13:00 when extended before timezone.
With quarterOfYear, duration and objectSupport all extended before utc + timezone (expected 12:00-04:00 for each):
dev |
164e3d4 |
4f919e9 |
|
|---|---|---|---|
dayjs.tz('2021-01-15 12:00', NY).add(1, 'quarter') |
12:00-05:00 | 13:00-04:00 | ✅ 12:00-04:00 |
dayjs.tz('2021-03-13 12:00', NY).add(dayjs.duration(1, 'day')) |
12:00-05:00 | 13:00-04:00 | ✅ 12:00-04:00 |
dayjs.tz('2021-03-13 12:00', NY).add({ days: 1 }) |
12:00-05:00 | 13:00-04:00 | ✅ 12:00-04:00 |
Extended after timezone, all three were already right on 164e3d4 and still are.
What changed:
- Quarters,
Durations and any object value now get handed to the previousaddon the zoned instance (unit === Q || (number !== null && typeof number === 'object')). The other plugins split them into units, which come back through the DST-awareadd. - That alone wasn't enough for
objectSupport: it added each key with theaddit captured at extend time (core), so the units never reachedtimezone. It now goes throughthis.add, which gives the same result whentimezoneisn't in the picture.
There's a new Plugin extension order block in the tests that loads a separate dayjs for each order. It covers quarters, durations (including { days: 1, hours: 1 }) and objects with add and subtract, and it fails on 164e3d4 and passes now.
One side thing I ran into when trying the alphabetical order: quarterOfYear's add runs Number(number) on everything before checking the unit. So if it's extended after duration or objectSupport, it breaks them, even without timezone. On dev:
dayjs.extend(duration); dayjs.extend(objectSupport); dayjs.extend(quarterOfYear)
dayjs('2021-01-31').add({ months: 1 }) // Invalid Date
dayjs('2021-01-31').add(dayjs.duration({ months: 1 })) // 2021-03-02 10:00 (~30.4 days of ms)I kept that out of this PR and the tests extend quarterOfYear first. Happy to send a separate small fix that moves the coercion into the quarter branch.
…tension order - Return an invalid instance (keeping its zone and locale) instead of throwing a RangeError from Intl when a zoned operation ends up invalid: startOf/endOf on an invalid zoned instance, or add/subtract/set with NaN on a valid one. - Hand quarters, durations and objects to the previous add on the zoned instance, so quarterOfYear, duration and objectSupport split them into units that come back through the DST-aware add, whichever order the plugins were extended in. - objectSupport adds each key through the full add chain instead of the add it captured, so plugins extended after it still see every unit. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Thanks @UnderHear, confirmed. I ran every example: on Fixed in 4f919e9:
New tests in
Each assertion checks |
Summary
Fixes DST bugs in calendar arithmetic on zoned instances (
add/subtractwith calendar units, setters,startOf/endOf) and intz(zone, true). Following the scope agreed in #3169, the fix lives insrc/plugin/timezone/index.js: no changes toDayjs.prototypeor theutcplugin. It's built on the existingtzOffset/fixOffsetprimitives. The only other change is a small one inobjectSupport(see Fix), so its object values also reach the DST-awareadd.Closes #1271
Closes #2609
Related: #3169 (this implements the follow-up described there), #3174, mui/mui-x#10584
devdayjs.tz('2020-10-24', 'Europe/London').add(2, 'day')→2020-10-26T00:00:00+01:00; should be+00:00tz(zone, true)is an hour off (#2609 comment, Los Angeles host)dayjs('2025-11-01T23:00').tz('America/New_York', true)→04:00Z; should be03:00ZstartOflands on the wrong offset or day (#2609, US host; #3169 report, Athens host)dayjs.tz('2023-10-30', 'Europe/Paris').startOf('week')→+01:00; should be+02:00dayjs.tz('2024-03-10', 'America/Los_Angeles').format()→2024-03-09T23:00:00-08:00dayjs.tz('2012-11-04 01:30', 'America/New_York')is-04:00in summer and-05:00in winter. This is whyparses the fall-back overlap the same way as momentcurrently fails ondevevery winter.adjustOffset)timezone="Europe/London"on a Paris host (dayjs 1.11.10)Root cause
A zoned instance stores one fixed
$offset, plus a host-localDateshifted so that its local fields show the zone's wall clock.add/setcopy that$offsetthroughUtils.w, so the offset is never looked up again after crossing a DST change.tz(zone, true)andstartOftook the target offset at the wrong instant (the wall time read as host local time), then adjusted by the difference.d(ts).utcOffset(offset)shifts the hostDatebyoffset + hostOffset. If that shift crosses a host DST change, the local fields are an hour off.dayjs.tz(string, zone)seededfixOffsetwith the zone's offset atDate.now().Fix (timezone plugin only)
fromWallClock(wallTs, zone, guess): resolves the instant withfixOffset, then builds the instance from a host-localDatewhose fields already show the zone's wall clock, and attaches the offset withutcOffset(offset, true). That path never shifts across a host DST change. Every zoned instance is now built this way, includingd.tz,tz()andtz(zone, true).add/subtract:set,startOfandendOfwork on the wall clock the same way, and keep locale-aware week starts.dayjs.tz(string, zone)seedsfixOffsetwith the offset from a day earlier, so an ambiguous fall-back time always resolves to the earlier instant, like moment, whatever today's date is.startOf/endOfon an invalid zoned instance, oradd/subtract/setwithNaN), it returns an invalid instance that keeps its zone and locale. It no longer reachesIntl.DateTimeFormatwith an invalidDate, which throws aRangeError. Thanks to the review from UnderHear.Durations and object values are handed to the previousaddon the zoned instance.quarterOfYear,durationandobjectSupportthen split them into plain units that come back through the DST-awareadd, whether they were extended before or aftertimezone. Thanks to bardrop's review.objectSupportnow adds each key throughthis.addinstead of theaddit captured when extended. Otherwise, extended beforetimezone, its units would skip the timezone plugin entirely. Withouttimezonethe result is the same.Not in this PR:
quarterOfYearrunsNumber()on every value itsaddreceives. Extended afterdurationorobjectSupport, it breaks them ondeveven withouttimezone(add({ months: 1 })is Invalid Date, and a 1-month duration is added as ~30.4 days of milliseconds). That's a separate fix; the tests here extendquarterOfYearfirst.Evidence
Each scenario is run in Chromium with the machine time zone emulated (Playwright
timezoneId) and the clock frozen to the date of the original report (page.clock.setFixedTime). The same page is built against dayjsv1.11.10(as reported),dev(d3e43be) and this branch. moment-timezone 0.6.6 is the reference. The harness, screenshots and JSON results are on this evidence branch, which isn't for merging.dayjs.tz,startOftz(zone, true)add(1, 'day')walk,startOf<DateCalendar timezone="Europe/London">#1271: before → after
#2609: before → after
mui-x#10584: v1.11.10 (as reported) → this PR. The left calendar in each screenshot uses MUI X 6.16's
adjustOffset; the right one uses the current MUI X 9.18 adapter.On
devthe calendar no longer shows a duplicate, but the offsets produced byadd(1, 'day')are still wrong (screenshot). Current MUI X also works around this inside its adapter.Side-by-side recordings: #1271 · #2609 · mui-x#10584 · fall-back overlap
Tests added
In
test/plugin/timezone.test.js, underDST-aware calendar arithmetic vs moment:add/subtractwith day, week, month and year across spring-forward and fall-back, in New York, Paris, Sydney and Londondate,month,hour,minute) across DSTstartOf/endOf(week,day) across DST, including thestartOf('day')case reported on fix(timezone): stop inheriting host DST in instance .tz() offset #3169 (Athens host)tz(zone, true)across DST (DayJS Timezone Bug with Daylight Savings #2609), including 03:00:01 on LA's spring-forward daykeepLocalTimeintoAmerica/Guadeloupeon the EU spring-forward day, the case left out of fix(timezone): compute instance .tz() offset without host DST #3174 (fails ondevon Paris/London hosts)Also in
test/plugin/timezone.test.js:Invalid dates through zoned operations:startOf/endOfandadd/subtract/seton an invalid zoned instanceNaNfor every unit (day to millisecond) onadd/subtract, and for date, month, year, hour and minute onsetisValid(),format(), the zone and the localePlugin extension order (quarterOfYear, duration, objectSupport): loads a separate dayjs with those plugins extended aftertimezone, then before it. For each order it checks quarters, durations (including{ days: 1, hours: 1 }) and objects withaddandsubtractacross the New York spring-forward.package.json:test-tz-pluginalso runs on anAmerica/Los_Angeleshost. Paris, London, New York and Auckland didn't catch the host-DST bug: ondev, four existingDST, a time that never existedtests fail on a Los Angeles host.In a few cases the moment versions pinned in
devDependencies(moment 2.29.2, moment-timezone 0.5.31) are wrong on some hosts: theirkeepLocalTimelands an hour off, and adding a day into a spring-forward gap gives a host-dependent result. Current moment (2.31.0) agrees with this PR on all of them. Those tests assert explicit values, checked against parsing the wall time in the zone, instead ofmatchMoment. Upgrading the pinned moment would let them go back tomatchMoment, but that's out of scope here.Test plan
npm testwithTZ=UTC(same as CI): lint OK, 819/819 tests, 100% line coverageTZ=<zone> npm run test-tz-pluginpasses (79/79) for UTC, Europe/Paris, Europe/London, America/New_York, America/Los_Angeles, Pacific/Auckland, Asia/Tokyo and America/Sao_Paulo. Earlier commits were also run on America/Chicago, Pacific/Honolulu and Europe/Athens.164e3d4) and pass nowutcplugin and core are unchanged (git diff dev -- src/index.js src/plugin/utcis empty)Heads-up for contributors and reviewers: test results depend on the machine time zone
This PR also adds a note about this to
CONTRIBUTING.md.new Date(0),'2015-01-01T00:00:00.000Z'), so their expected values only hold on a machine at or ahead of UTC. On a cleandevcheckout:dayOfYear"DayOfYear set" andlocalizedFormat"Should not interpolate characters inside square brackets" fail. For example,new Date(0)is still 1969 in New York.get-set/pluralGetSet"Set Month and Year in last day of month" andcalendar"ReferenceTime" fail.TZ=UTC npm testreproduces CI locally.Known limitation (unchanged by this PR)
If a zone's wall time doesn't exist on the host (it falls in the host's own spring-forward gap), no host-local
Datecan represent it. For example, Lord Howe Island2024-10-06 02:45on anAustralia/Sydneyhost. The existing testhandles the 30-minute Lord Howe gap...fails on a Sydney host on bothdevand this branch. Sydney isn't in the CI host list. Fixing this would need zoned instances stored in a host-independent form, which is a larger change than this plugin-scoped fix.For comparison, I ran #3169's branch (
334d25a) against its own extra tests and this PR's tests:devdayjs('2023-10-29').tz('Europe/Paris', true)on a US host (+02:00)tz('America/Los_Angeles', true)at 03:00:01 on spring-forward day (-07:00)utcplugin unchanged#3169's approach handles the host-gap case above, which this PR can't; it does so by changing the
utcplugin and core. Glad to adjust in whichever direction you prefer.Credits
Builds on the investigation and tests in #3169 and #3174. This PR was prepared with Claude Code.
🤖 Generated with Claude Code