Skip to content

fix(timezone): re-resolve the zone offset in calendar math across DST - #3363

Open
dacheng-sa wants to merge 5 commits into
iamkun:devfrom
dacheng-sa:fix/timezone-dst-arithmetic
Open

dacheng-sa wants to merge 5 commits into
iamkun:devfrom
dacheng-sa:fix/timezone-dst-arithmetic

Conversation

@dacheng-sa

@dacheng-sa dacheng-sa commented Nov 13, 2026 •

Copy link
Copy Markdown

Summary

Fixes DST bugs in calendar arithmetic on zoned instances (add/subtract with calendar units, setters, startOf/endOf) and in tz(zone, true). Following the scope agreed in #3169, the fix lives in src/plugin/timezone/index.js: no changes to Dayjs.prototype or the utc plugin. It's built on the existing tzOffset/fixOffset primitives. The only other change is a small one in objectSupport (see Fix), so its object values also reach the DST-aware add.

Closes #1271
Closes #2609
Related: #3169 (this implements the follow-up described there), #3174, mui/mui-x#10584

Symptom on dev Example
Adding days keeps the old offset (#1271) dayjs.tz('2020-10-24', 'Europe/London').add(2, 'day') → 2020-10-26T00:00:00+01:00; should be +00:00
tz(zone, true) is an hour off (#2609 comment, Los Angeles host) dayjs('2025-11-01T23:00').tz('America/New_York', true) → 04:00Z; should be 03:00Z
startOf lands 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:00
Wall clock wrong when the host changes DST at a different time (#2609, New York host) dayjs.tz('2024-03-10', 'America/Los_Angeles').format() → 2024-03-09T23:00:00-08:00
Ambiguous fall-back parse depends on today's date dayjs.tz('2012-11-04 01:30', 'America/New_York') is -04:00 in summer and -05:00 in winter. This is why parses the fall-back overlap the same way as moment currently fails on dev every winter.
Duplicate day in a calendar grid (mui-x#10584, with MUI X 6.16's adjustOffset) Oct 29, 2023 rendered twice for timezone="Europe/London" on a Paris host (dayjs 1.11.10)

Root cause

A zoned instance stores one fixed $offset, plus a host-local Date shifted so that its local fields show the zone's wall clock.

  1. Core add/set copy that $offset through Utils.w, so the offset is never looked up again after crossing a DST change.
  2. tz(zone, true) and startOf took the target offset at the wrong instant (the wall time read as host local time), then adjusted by the difference.
  3. d(ts).utcOffset(offset) shifts the host Date by offset + hostOffset. If that shift crosses a host DST change, the local fields are an hour off.
  4. dayjs.tz(string, zone) seeded fixOffset with the zone's offset at Date.now().

Fix (timezone plugin only)

  • fromWallClock(wallTs, zone, guess): resolves the instant with fixOffset, then builds the instance from a host-local Date whose fields already show the zone's wall clock, and attaches the offset with utcOffset(offset, true). That path never shifts across a host DST change. Every zoned instance is now built this way, including d.tz, tz() and tz(zone, true).
  • add/subtract:
    • Calendar units (day, week, month, year) are applied to the wall clock as a UTC-mode instance, then resolved back.
    • Exact units (h/m/s/ms) add elapsed time to the real instant, then convert back.
  • set, startOf and endOf work on the wall clock the same way, and keep locale-aware week starts.
  • Ambiguous results:
    • Arithmetic and setters keep the current offset when it's still valid, like moment.
    • dayjs.tz(string, zone) seeds fixOffset with 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.
  • Invalid results: when a zoned operation ends up invalid (startOf/endOf on an invalid zoned instance, or add/subtract/set with NaN), it returns an invalid instance that keeps its zone and locale. It no longer reaches Intl.DateTimeFormat with an invalid Date, which throws a RangeError. Thanks to the review from UnderHear.
  • Plugin extension order: quarters, Durations and object values are handed to the previous add on the zoned instance. quarterOfYear, duration and objectSupport then split them into plain units that come back through the DST-aware add, whether they were extended before or after timezone. Thanks to bardrop's review.
  • objectSupport now adds each key through this.add instead of the add it captured when extended. Otherwise, extended before timezone, its units would skip the timezone plugin entirely. Without timezone the result is the same.

Not in this PR: quarterOfYear runs Number() on every value its add receives. Extended after duration or objectSupport, it breaks them on dev even without timezone (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 extend quarterOfYear first.

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 dayjs v1.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.

Scenario Machine v1.11.10 dev this PR
#1271: add day/month/hour across DST America/Santiago 0/5 0/5 5/5
#2609: dayjs.tz, startOf America/New_York 1/4 1/4 4/4
#2609 comment: tz(zone, true) America/Los_Angeles 0/2 0/2 2/2
mui-x#10584: add(1, 'day') walk, startOf Europe/Paris 1/3 1/3 3/3
mui-x#10584: real <DateCalendar timezone="Europe/London"> Europe/Paris duplicate 29 ok ok
Ambiguous fall-back parse, clock in winter Europe/Paris 0/1 0/1 1/1

#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 dev the calendar no longer shows a duplicate, but the offsets produced by add(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, under DST-aware calendar arithmetic vs moment:

Also in test/plugin/timezone.test.js:

  • Invalid dates through zoned operations:
    • startOf/endOf and add/subtract/set on an invalid zoned instance
    • NaN for every unit (day to millisecond) on add/subtract, and for date, month, year, hour and minute on set
    • the locale kept on the invalid result
    • each assertion checks isValid(), format(), the zone and the locale
  • Plugin extension order (quarterOfYear, duration, objectSupport): loads a separate dayjs with those plugins extended after timezone, then before it. For each order it checks quarters, durations (including { days: 1, hours: 1 }) and objects with add and subtract across the New York spring-forward.

package.json: test-tz-plugin also runs on an America/Los_Angeles host. Paris, London, New York and Auckland didn't catch the host-DST bug: on dev, four existing DST, a time that never existed tests 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: their keepLocalTime lands 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 of matchMoment. Upgrading the pinned moment would let them go back to matchMoment, but that's out of scope here.

Test plan

  • npm test with TZ=UTC (same as CI): lint OK, 819/819 tests, 100% line coverage
  • TZ=<zone> npm run test-tz-plugin passes (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.
  • The new invalid-date and plugin-order tests (8) fail on the previous commit (164e3d4) and pass now
  • The utc plugin and core are unchanged (git diff dev -- src/index.js src/plugin/utc is 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.

  • Day.js reads and formats in the machine's local time. Several existing tests use fixed UTC timestamps (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 clean dev checkout:
    • Behind UTC (New York, Los Angeles, São Paulo, Honolulu): dayOfYear "DayOfYear set" and localizedFormat "Should not interpolate characters inside square brackets" fail. For example, new Date(0) is still 1969 in New York.
    • UTC+10 or more (Auckland, Lord Howe): get-set/pluralGetSet "Set Month and Year in last day of month" and calendar "ReferenceTime" fail.
    • These are test assumptions, not library bugs, and this PR doesn't change them. CI runs in UTC, so TZ=UTC npm test reproduces CI locally.
  • Separately, the timezone tests are run under fixed zones on purpose, and some timezone behaviour really is host-dependent. That is why this PR adds a Los Angeles host run.

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 Date can represent it. For example, Lord Howe Island 2024-10-06 02:45 on an Australia/Sydney host. The existing test handles the 30-minute Lord Howe gap... fails on a Sydney host on both dev and 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:

Case dev #3169 this PR
Guadeloupe wall time inside the host's spring-forward gap (Paris host) ✗ ✓ ✗
dayjs('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) ✗ ✗ ✓
Leaves core and the utc plugin unchanged – ✗ ✓

#3169's approach handles the host-gap case above, which this PR can't; it does so by changing the utc plugin 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

Dacheng Cheng and others added 3 commits November 13, 2026 14:04
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 UnderHear left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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):

Suggested change
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.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 previous add on the zoned instance (unit === Q || (number !== null && typeof number === 'object')). The other plugins split them into units, which come back through the DST-aware add.
  • That alone wasn't enough for objectSupport: it added each key with the add it captured at extend time (core), so the units never reached timezone. It now goes through this.add, which gives the same result when timezone isn'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>
@dacheng-sa

Copy link
Copy Markdown
Author

Thanks @UnderHear, confirmed. I ran every example: on 164e3d4 they threw RangeError: Invalid time value, while dev returned an invalid instance. While checking I also found valid.add(NaN, 'hour') returning an invalid instance without its $timezone.

Fixed in 4f919e9:

  • fromWallClock now returns an invalid instance that keeps its zone and locale before any Intl lookup. add/set/startOf all go through it, and endOf goes through startOf.
  • The elapsed-time path of add (h/m/s/ms) does the same, so add(NaN, 'hour') keeps its timezone too.
  • d.tz('invalid', zone) reuses the same helper.
dev 164e3d4 4f919e9
dayjs.tz('invalid', 'Europe/Skopje').startOf('day') Invalid (no tz) throws Invalid, keeps tz
….endOf('day') Invalid (no tz) throws Invalid, keeps tz
dayjs.tz('2024-01-15', 'Europe/Paris').add(NaN, 'day') Invalid, keeps tz throws Invalid, keeps tz
….set('date', NaN) Invalid, keeps tz throws Invalid, keeps tz
….add(NaN, 'hour') Invalid, keeps tz Invalid (no tz) Invalid, keeps tz

New tests in Invalid dates through zoned operations cover:

  • startOf/endOf (day, month, week) on an invalid zoned instance.
  • add/subtract/set on an invalid zoned instance.
  • add/subtract with NaN for every unit, from day to millisecond.
  • set with NaN for date, month, year, hour and minute.
  • The locale (fr) being kept on the invalid result.

Each assertion checks isValid(), format(), $x.$timezone and $L. All 5 tests fail on 164e3d4 and pass now.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

DayJS Timezone Bug with Daylight Savings Add days across Daylight Saving Time

3 participants