dayjs icon indicating copy to clipboard operation
dayjs copied to clipboard

isTomorrow, isToday plugins do not account for time zone.

Open charliejlevine opened this issue 2 years ago • 1 comments

Describe the bug isTomorrow, isTomorrow, isYesterday plugins do not seem to account for time zone, which affects whether a given day is yesterday, today, or tomorrow. If it's 11:59PM PST January 1, then January 2 is tomorrow, but in EST, where it is, 3:59AM, it is today. So would timezone then need to be incorporated into this plugin?

Expected behavior In my case, this solves it. For tomorrow and yesterday, I just add or subtract 1 day from d2.

`const d1 = dayjs(date).tz(timeZone).dayOfYear(); const d2 = dayjs().tz(timeZone).dayOfYear(); if (d1 === d2) isToday = true

Information

  • Day.js Version [e.g. v1.11.1]
  • OS: [e.g. Node]
  • Browser [Chrome v100]
  • Time zone: [GMT-07:00 DST (Pacific Daylight Time)]

charliejlevine avatar May 06 '22 18:05 charliejlevine

If I understand your problem (using the 'today' variant), you are trying to find out if a date in a given time zone is the same day as in another time zone.

As you already stated, dayjs functions 'isToday' and 'isTomorrow' use the current time in the current time zone as a reference ("now()").

Your solution is a good work around.

Another possibility would be to use the 'isSame' function:

// isToday with 'isSame'
function isSameDay(date1, date2) {
  let result = false
  if (dayjs.isDayjs(date1) && dayjs.isDayjs(date2)) {
    result = date1.isSame(date2, 'day')
  }
  return result
}
// isTomorrow with 'isSame' - tomorrow = date1 + 1 day
function isNextDay(date1, date2) {
  let result = false
  if (dayjs.isDayjs(date1) && dayjs.isDayjs(date2)) {
    const tomorrowDate = date1.add(dayjs.duration({ days: 1 }))
    result = tomorrowDate.isSame(date2, 'day')
  }
  return result
}

// as an example I use 'GMT' as a starting point - the local time zone would be just as good
const currentDate = dayjs.tz('2022-01-01T23:59:00', 'GMT')

// reference is later time zone (to the east - Europe/Berlin)
const referenceDateSameTz = currentDate.tz('Europe/Berlin')
// isToday with 'isSame'
console.log(isSameDay(currentDate, referenceDateSameTz))  // true
// isTomorrow with 'isSame'
console.log(isNextDay(currentDate, referenceDateSameTz))  // false
console.log(isNextDay(currentDate, referenceDateSameTz.add(dayjs.duration({ hours: 1 }))))  // true

// reference is earlier time zone (to the west - America/New_York)
const referenceDateOtherTz = currentDate.tz('America/New_York')
// isToday with 'isSame'
console.log(isSameDay(currentDate, referenceDateOtherTz)) // true
// isTomorrow with 'isSame'
console.log(isNextDay(currentDate, referenceDateOtherTz)) // false

It is important that the dates are generated with the corresponing time zone (dayjs.tz(date-string, tz-name).

BePo65 avatar Jun 06 '22 13:06 BePo65

@BePo65 thanks, this solved my problem!

varave avatar Jul 22 '23 10:07 varave