t1m0n / air-datepicker

Lightweight, dependency-free JavaScript datepicker.
https://air-datepicker.com
MIT License
2.58k stars 1.36k forks source link

selectDate #589

Closed cloudymeatball closed 4 months ago

cloudymeatball commented 4 months ago

Problem

selectDate() behaves differently depending on whether the input is properly formatted or not. This leads to a properly formatted input date goes to previous day when system timezone is west of UTC +0.

Background

I want the user to be able to enter a day on keyboard, and the datepicker should highlight that day. This works with a malformed date, such as 2024-2-26. But if the value is instead 2024-02-26, it converts 2024-02-26T00:00:00.000Z to my local timezone in the Americas, then show '2024-02-25'. This occurs with every focusin and focusout of the fie, either by mouse or by tabbing. I am only working with date, and it seems to be the same regardless what I put for updateTime, or whether I wrap the '2024-02-26in anew Date()`.

Reproduction

I couldn't quite get css to work in stackblitz, but you can 1) change system timezone to any Americas timezone and 2) go to https://stackblitz.com/edit/sveltejs-kit-template-default-uzophc?file=src%2Froutes%2F%2Bpage.svelte. 3) observe the differences between typing in 2024-02-26 and 2024-2-26.

cloudymeatball commented 4 months ago

A workaround is

let localDate = new Date(date)
localDate.setDate(localDate.getUTCDate())
datepicker.selectDate(localDate)

This basically adds 24 hours when local date is one less than UTC date.

t1m0n commented 4 months ago

Hi! Yeah, it seems like a problem =(. Thank you for a bug report, I'll see what I can do about it.

t1m0n commented 4 months ago

A workaround is

let localDate = new Date(date)
localDate.setDate(localDate.getUTCDate())
datepicker.selectDate(localDate)

This basically adds 24 hours when local date is one less than UTC date.

It is not good idea, because you will get wrong dates in edge cases, when, for example, your date is '2024-03-01' you will get '2024-02-01` instead of what you'd expect.

cloudymeatball commented 4 months ago

@t1m0n yeah I ended up using the workaround in https://github.com/t1m0n/air-datepicker/issues/592, which fixes all sorts of month drop by 1 error, but your approach of modifying the string is most likely cleaner.