dayjs
dayjs copied to clipboard
Duration days is wrong between two dates
Describe the bug
The following code calculates the duration between two dates: (playground)
import dayjs from 'dayjs';
import duration from 'dayjs/plugin/duration';
dayjs.extend(duration);
const startDate = dayjs(new Date(2005, 4, 15));
const endDate = dayjs(new Date(2024, 7, 21));
const d = dayjs.duration(endDate.valueOf() - startDate.valueOf());
const result = {
startDate: startDate.format(),
endDate: endDate.format(),
display: d.format('Y [years], M [months], D [days]'),
days: d.days(),
months: d.months(),
years: d.years(),
totalDays: d.asDays(),
totalMonths: d.asMonths(),
totalYears: d.asYears(),
};
Result using [email protected] and [email protected] is:
{
"startDate": "2005-05-15T00:00:00+01:00",
"endDate": "2024-08-21T00:00:00+01:00",
"display": "19 years, 3 months, 11 days",
"days": 11,
"months": 3,
"years": 19,
"totalDays": 7038,
"totalMonths": 231.38630136986302,
"totalYears": 19.28219178082192
}
Result using dayjs <= 1.11.09 is:
{
"startDate": "2005-05-15T00:00:00+01:00",
"endDate": "2024-08-21T00:00:00+01:00",
"display": "19 years, 3 months, 13 days",
"days": 13,
"months": 3,
"years": 19,
"totalDays": 7038,
"totalMonths": 234.6,
"totalYears": 19.28219178082192
}
The result of the code when using diff
(playground) is not different.
const startDate = dayjs('2005-05-15');
const endDate = dayjs('2024-08-21');
const d = dayjs.duration(endDate.diff(startDate));
Expected behavior
days
value should be 6
.
display
value should be 19 years, 3 months, 6 days
.
totalMonths
value should be 231.##
.
I understand that dayjs is calculating the number of Milliseconds and then dividing it by number of milliseconds in the year, month, etc, to find the result for them.
But when we say the duration between two dates are 19 years, 3 months and 11 days
, those 19 years are not equal in the number of milliseconds.
I think the following line of code doesn't consider leap years:
const MILLISECONDS_A_YEAR = MILLISECONDS_A_DAY * 365
There are 4 leap years between the above days, and 11 will reduce to 7.
Information
- Day.js Version 1.11.11
- OS: Windows 11
- Browser: node v18.20.1
- Time zone: BST
Related issue: #2464