Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Specify a custom date string parser #5289

Open
duncan-oxd opened this issue Dec 23, 2024 · 0 comments
Open

Specify a custom date string parser #5289

duncan-oxd opened this issue Dec 23, 2024 · 0 comments

Comments

@duncan-oxd
Copy link

Is your feature request related to a problem? Please describe.

I want to allow date inputs typed or pasted in various formats, but JS parses "YYYY-MM-DD" inputs in a different timezone than "DD MM YYYY" or eg "March 15 2022"

If the user is in California and types "2022-03-15", the calendar will highlight/select March 14 instead of March 15 because it assumes they mean UTC time, and March 15 midnight in UTC is still March 14 in California.
If the user in California types "March 15, 2022", the calendar will correctly select March 15 because it uses local time.

Describe the solution you'd like

If JS guesses the timezone, I can code around this by writing a custom date parser function, and I'd like to be able to have the date picker use that instead of the native Date parsing.

Describe alternatives you've considered

Currently, I'm using date-fns and specifically handling the enter key event:

// component props:
onChange={() => {
  // Required prop, but handled by onSelect/onKeyDown
}}
onKeyDown={(event) => onKeyDown(event)}
onSelect={(date) => setDate(date)}

// ---

// keydown handler:
function onKeyDown(event) {
  // If the input is in the text field and Enter is pressed,
  // try parsing the date. Otherwise allow keyboard navigation as usual.
  if (!event.target.value || event.key !== "Enter") return;

  // Try parsing date as YYYY-MM-DD first, and correct for time zone
  // because JS treats it as UTC time but other strings as local time.
  let date = dateFns.parse(event.target.value, "yyyy-MM-dd", new Date());

  // Try parsing any other date string if parsing YYYY-MM-DD fails
  if (!isValid(date)) {
    date = new Date(event.target.value);

    // Don't set the time if it can't be parsed
    if (!isValid(date)) return;

    setDate(date);
  }
}

Additional context

An alternative would be to build the functionality into the component, or allow us to specify a timezone to parse all dates with, but you'd probably prefer to keep it lean and let us do it if we need.

This feature request would resolve a bunch of open and stale tickets related to the same issue I'm describing. #4414, #5190, #4223, #1018, and others.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant