Skip to content

Commit

Permalink
Fix differenceInDays across DST (closes #533) (#1630)
Browse files Browse the repository at this point in the history
  • Loading branch information
dcousens authored and kossnocorp committed Apr 14, 2020
1 parent 0d0918f commit 35a5bbe
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 12 deletions.
20 changes: 8 additions & 12 deletions src/differenceInDays/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import toDate from '../toDate/index.js'
import differenceInCalendarDays from '../differenceInCalendarDays/index.js'
import compareAsc from '../compareAsc/index.js'
import requiredArgs from '../_lib/requiredArgs/index.js'

/**
Expand All @@ -10,6 +8,8 @@ import requiredArgs from '../_lib/requiredArgs/index.js'
*
* @description
* Get the number of full day periods between the given dates.
* This function returns the difference in days as an integer whole number of 24 hour periods between two timestamps, and thereby ignores DST changes.
*
*
* ### v2.0.0 breaking changes:
*
Expand All @@ -36,21 +36,17 @@ import requiredArgs from '../_lib/requiredArgs/index.js'
* )
* //=> 0
*/
var MILLISECONDS_IN_DAY = 86400000

export default function differenceInDays(dirtyDateLeft, dirtyDateRight) {
requiredArgs(2, arguments)

var dateLeft = toDate(dirtyDateLeft)
var dateRight = toDate(dirtyDateRight)

var sign = compareAsc(dateLeft, dateRight)
var difference = Math.abs(differenceInCalendarDays(dateLeft, dateRight))

dateLeft.setDate(dateLeft.getDate() - sign * difference)
var result = (dateLeft - dateRight) / MILLISECONDS_IN_DAY

// Math.abs(diff in full days - diff in calendar days) === 1 if last calendar day is not full
// If so, result must be decreased by 1 in absolute value
var isLastDayNotFull = compareAsc(dateLeft, dateRight) === -sign
var result = sign * (difference - isLastDayNotFull)
// Prevent negative zero
return result === 0 ? 0 : result
// round towards zero
if (result > 0) return Math.floor(result)
return Math.ceil(result)
}
10 changes: 10 additions & 0 deletions src/differenceInDays/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,16 @@ describe('differenceInDays', function() {
assert(result === 0)
})

it('ignores any localtime differences with DST', function() {
const a = new Date('2019-10-05T15:00:00.000Z') // for TZ=Australia/Sydney, this is 1 hour before DST
const b = new Date('2019-10-06T14:00:00.000Z') // for TZ=Australia/Sydney, this is 1 day after DST
const c = new Date('2019-10-07T14:00:00.000Z') // for TZ=Australia/Sydney, this is 2 days after DST

assert(differenceInDays(c, b) === 1)
assert(differenceInDays(b, a) === 0) // 23 hours < 1 day
assert(differenceInDays(c, a) === 1) // 47 hours < 2 days
})

it('does not return -0 when the given dates are the same', () => {
function isNegativeZero(x) {
return x === 0 && 1 / x < 0
Expand Down

0 comments on commit 35a5bbe

Please sign in to comment.