Dayjs: diff() in "days" broken after making add() "days" aware of daylight-saving changes

Created on 15 Oct 2018  路  2Comments  路  Source: iamkun/dayjs

Computing difference between two dates, which one was subtracted 1000 days from, returns 999 days, if the date is on the boundary of daylight-saving changes:

> d1 = dayjs('2018-10-28')
2018-10-27T22:00:00.000Z
> d2 = dayjs('2018-10-28').add(-1000, 'days')
2016-01-31T23:00:00.000Z
> d1.diff(d2, 'hours')
23999
> d1.diff(d2, 'days')
999

Moment.js computes the difference correctly. Notice, that the difference in hours is correct in Day.js too:

> m1 = moment('2018-10-28')
moment("2018-10-28T00:00:00.000")
> m1.toDate()
2018-10-27T22:00:00.000Z
> m2 = moment('2018-10-28').add(-1000, 'day')
moment("2016-02-01T00:00:00.000")
> m2.toDate()
2016-01-31T23:00:00.000Z
> m1.diff(m2, 'hours')
23999
> m1.diff(m2, 'days')
1000

This problem has been caused by 969acedc94461dca2b1d9313299a2c9db4aed7a9. It adds/subtracts days using the local time zone. Previously, days were added/subtracted in UTC (using UNIX time), like hours and shorter units. While it helps people, who were not aware of Day.js working in the local time zone (#262 and #329), it also made Day.js inconsistent, because computing difference in days is still done in UTC (using UNIX time).

Once add() and subtract() methods were modified to expect the day count in the local time zone, the diff() method should be modified to return the day count in the local time zone too.

Adding/subtracting hours and shorter units happens in UTC, computing the difference in these units happens in UTC as well. Handling hours and shorter units by Day.js is consistent.

The tests were executed in Node.js 8 in the time zone "Europe/Prague" using Day.js 1.7.7 and Moment.js 2.22.2.

released

Most helpful comment

:tada: This issue has been resolved in version 1.8.2 :tada:

The release is available on:

Your semantic-release bot :package::rocket:

All 2 comments

Related: Adding one 'day' on a daylight-changing day is broken. It adds 24 hours, no matter if that day has 23, 24 or 25 hours.

let a = dayjs('2018-11-04');
console.log(a);
// h聽{$d: Sun Nov 04 2018 00:00:00 GMT-0400 (Eastern Daylight Time), $y: 2018, $M: 10, $D: 4, ...}
a = a.add(1, 'day');
console.log(a);
// h聽{$d: Sun Nov 04 2018 23:00:00 GMT-0500 (Eastern Standard Time), $y: 2018, $M: 10, $D: 4,聽鈥

:tada: This issue has been resolved in version 1.8.2 :tada:

The release is available on:

Your semantic-release bot :package::rocket:

Was this page helpful?
0 / 5 - 0 ratings

Related issues

idasbiste picture idasbiste  路  4Comments

oliv9286 picture oliv9286  路  4Comments

dakshshah96 picture dakshshah96  路  5Comments

g1eny0ung picture g1eny0ung  路  4Comments

vaquel picture vaquel  路  3Comments