Skip to content

Commit

Permalink
fix: getToday() uses the correct initial date
Browse files Browse the repository at this point in the history
  • Loading branch information
lhermann committed Apr 16, 2024
1 parent 873db51 commit 9502436
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 4 deletions.
6 changes: 2 additions & 4 deletions getToday.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import getTimezoneOffset from 'date-fns-tz/getTimezoneOffset'
import addMilliseconds from 'date-fns/addMilliseconds'
import addMinutes from 'date-fns/addMinutes'

/**
* Get the Date of 0:00 today in the given timezone
Expand All @@ -13,9 +12,8 @@ export default function getToday (timezone = undefined, now = undefined) {
if (now !== undefined && !(now instanceof Date)) {
throw new Error('The 2nd argument must be undefined or an instance of date.')
}
// Step 1: Undo system timezone for new Date() (system -> UTC)
const inSystem = new Date()
const inUTC = now || addMinutes(inSystem, -inSystem.getTimezoneOffset())
// Step 1: Determine now (new Date() carries no timezone info, always in UTC)
const inUTC = now || new Date()

// Step 2: Apply target timezone (UTC -> zoned)
const tzOffset = timezone ? getTimezoneOffset(timezone, inUTC) : 0
Expand Down
4 changes: 4 additions & 0 deletions tests/getToday.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ describe('applyDate', () => {
// Tue Oct 03 2023 01:30:00 GMT+0000 (UTC)
const today2 = getToday(tz, new Date('2023-10-03T01:30:00.000Z'))
expect(today2.toISOString()).to.equal('2023-10-03T00:00:00.000Z')

// Tue Apr 16 2024 15:01:22 GMT+0000 (UTC)
const today3 = getToday(tz, new Date('2024-04-16T15:01:22.871Z'))
expect(today3.toISOString()).to.equal('2024-04-16T00:00:00.000Z')
})

test('Europe/Berlin', () => {
Expand Down
6 changes: 6 additions & 0 deletions tests/isSameDay.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,10 @@ describe('isSameDay', () => {
const date2 = new Date('2024-04-11T00:00:00Z')
expect(isSameDay(date1, date2, 'UTC')).to.be.false
})

test('AUS Date Picker bug', () => {
const date1 = new Date('2024-04-16T14:30:00.000Z')
const date2 = new Date('2024-04-16T00:00:00.000Z')
expect(isSameDay(date1, date2, 'UTC')).to.be.true
})
})

0 comments on commit 9502436

Please sign in to comment.