iamkun / iamkun/dayjs

UTC offset is incorrect when using add

Open
#2,652 1 comment 5 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
48.7k
Forks
2.5k
PR merge metrics
No merged PRs in 30d

Description

**Describe the bug**
UTC offset is incorrect when doing dayjs().add()

When adding time to a given dayjs instance, if the resulting utc offset has changed, the $offset value in the dayjs instance remains the same and does not update, which leads to inaccuracy when using `utc` functions (which rely on the $offset being correct)

This bug is reported quite a few times, to name a few:
https://github.com/iamkun/dayjs/issues/2624
https://github.com/iamkun/dayjs/issues/2598
https://github.com/iamkun/dayjs/issues/2623
https://github.com/iamkun/dayjs/issues/2609

Upon inspecting the dayjs object:

```
const addedDate = dayjs.utc('2020-03-04T10:00:00Z').tz('America/New_York').add(1, 'week')
addedDate.utcOffset() // -300

// addedDate's $offset parameter = -300
```

```
const nonAddedDate = dayjs.utc('2020-03-11T10:00:00Z').tz('America/New_York')
nonAddedDate.utcOffset() // -240

// nonAddedDate's $offset parameter = -240
```

**Expected behavior**
Offset should update based on the resulting date after adding.

After adding a week,
```
const addedDate = dayjs.utc('2020-03-04T10:00:00Z').tz('America/New_York').add(1, 'week')
addedDate.utcOffset() // should be -240, not -300
```

**Possible fix**
`dayjs().add()` keeps the original utc offset of the input date, regardless if the resulting time's utcOffset has changed. When calling dayjs.add, maybe the $offset field should be updated in the `wrapper` function (line 55) which `.add()` calls to be based off the final date instead of copying the old offset over.

https://github.com/iamkun/dayjs/blob/3737c8c35459562d4e345136cbb83290e88c6692/src/index.js#L50-L56

**Information**
- Day.js 1.11.10
- OS: Mac
- Arc Browser 1.41.0
- Node 22
- Time zone: any, when changed with process.env as well.

Contributor guide

Open the contributing guide

Research direction

Start in src/index.js around lines 50-56, where the wrapper used by add() is described, and reproduce the America/New_York examples from the issue. Verify that adding across the daylight-saving transition produces the expected -240 utcOffset() and that the resulting instance's $offset matches it.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript
Domain
api
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.