Duration and diff seem to be incorrect for some cases
- Dominant language
- JavaScript
- Stars
- 48.7k
- Forks
- 2.5k
- PR merge metrics
- No merged PRs in 30d
Description
**Describe the bug**
Durations, durations, durations...
I am trying to replace `moment` with `dayjs` in my codebase and I almost have it....except date durations are killing, and despite having a look around, there doesn't seem to be an obvious fix.
1. I read that using `duration` with `diff` is a problem, so my first step was ditching `duration` (even if `moment` does work nicely...)
2. After the above, I thought it wouldn't be too difficult to calculate the `.diff` and then use `.add`/`.subtract` to calculate duration properly
Here's what I am doing (bit raw but just to show the issue):
```
const years = dayjs().diff(dayjs(date, 'YYYY-MM-DD'), 'years')
const months =
years === 0
? dayjs().diff(dayjs(date, 'YYYY-MM-DD'), 'months')
: dayjs().subtract(years, 'year').diff(dayjs(date, 'YYYY-MM-DD'), 'months')
const days =
months === 0
? dayjs().diff(dayjs(date, 'YYYY-MM-DD'), 'days')
: dayjs().subtract(months, 'month').diff(dayjs(date, 'YYYY-MM-DD'), 'days')
// Then I return a string with years/months or months/days depending on the granularity
```
**Expected behavior**
The start and end dates in my test are: `2022-04-06` and `2023-02-02`. Many sites calculate the duration as being 9 months and 27 days (or 28 if you include the end date)
With the code above I am getting 9 months and 26 days. I think it is related to `.subtract` because of the results it is returning but I am not sure.
```
moment('2023-02-02', 'YYYY-MM-DD').subtract(9, 'month').toString() // 'Mon May 02 2022 00:00:00 GMT+0100'
dayjs('2023-02-02', 'YYYY-MM-DD').subtract(9, 'month').toString() // 'Sun, 01 May 2022 23:00:00 GMT'
```
**Information**
- Day.js Version: 1.11.8
- OS: macOS Ventura
- Browser: Chrome 114
- Time zone: British Summer Time
Contributor guide
Research direction
The issue names no files or tests. Start by reproducing the provided dayjs and moment snippets with the 2022-04-06 and 2023-02-02 dates, then trace the subtract and diff entry points. Done should mean the discrepancy and expected inclusive or exclusive duration behavior are established, with a regression test if a bug is confirmed.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript
- Domain
- web-dev
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 28/100