Writing date in the input results in wrong date format #3636
Replies: 3 comments
-
I have the same problem, and the client I'm working with is insisting that this is fixed. Looks like I'm going to have to do some hacking until a dev can look at this and address the issue. |
Beta Was this translation helpful? Give feedback.
-
I found that the best solution for this is to use the DatePicker's onChangeRaw callback. This allows you to intercept the input changes and the process the attempted date being entered in a custom way. |
Beta Was this translation helpful? Give feedback.
-
I've also run into the aforementioned issue. The answer from @bjranson gives a clue as to how to solve it. For future reference, here is a concrete example of how I get rid of the issue: import ReactDatePicker from "react-datepicker";
import { parse, isValid } from "date-fns";
import { useState } from "react";
function parseDate(str: string, format: string) {
const parsed = parse(str, format, new Date());
if (isValid(parsed)) {
return parsed;
}
return undefined;
}
export function Example() {
const [date, setDate] = useState<Date | undefined>();
return (
<ReactDatePicker
dateFormat="d. M. yyyy"
showTimeSelect={false}
todayButton="Today"
dropdownMode="select"
isClearable
placeholderText="Click to select time"
shouldCloseOnSelect
onChange={(input) => {
// Using this method results in an inverted days and months issue.
// But it still needs to be used for clearing the input field (when using the ❌ button).
if (input === null) setDate(undefined);
}}
onChangeRaw={(e) => {
const trimmedInput = String(e.target.value).trim();
// In theory, the regex testing is unnecessary (but can prevent outlandish non-4-digit years).
if (/^\d{1,2}\.\s*\d{1,2}\.\s*\d{4}$/.test(trimmedInput)) {
setDate(parseDate(trimmedInput.replaceAll(" ", ""), "d.M.yyyy"));
}
}}
// Not sure here, but as I can recall, the selecting has to be done explicitly
onSelect={(date) => {
setDate(date);
}}
selected={date}
/>
);
} I hope it can help someone. However, it seems that this is a bug (and there is an issue opened). |
Beta Was this translation helpful? Give feedback.
-
Hi,
I have set the date format on my date picker as dd/MM/yyyy.
However, when the user writes a date in the input, for example 03/12/2022 (3. december 2022), the date picker value becomes 12/3/2022 (12. march 2022), so it looks like the date format is still the original for the user input.
Has anyone had this issue before and knows a solution?
Beta Was this translation helpful? Give feedback.
All reactions