i’m new to react , and i was struggling with changing the datePicker component format to dd-mm-yy instead of dd-mm-yyyy but it’s not working for me .
for more details: i want to be able to type date in a short year format DD-MM-YY
, and automatically the value in the input get parsed to yyyy-mm-dd.
this is my original code for dd-mm-yyyy format datePicker:
const CustomDatePicker: React.FC<CustomDatePickerProps> = forwardRef(
(
{
value,
onChange,
error,
placeholder,
customBorderColor = false,
customBgColor = false,
customIconColor = false,
required = false,
colorSchema = "primary",
disabled = false,
startDate,
endDate,
width,
baseColor = "#30BF4C",
},
ref
) => {
const [isOpen, setOpen] = useState<boolean>(false);
const datepickerRef = useRef<HTMLDivElement | null>(null);
const [validationError, setValidationError] = useState<string | null>(null);
const toast = useToast();
const handleDocumentClick = (event: MouseEvent) => {
if (
datepickerRef?.current &&
event?.target instanceof Node &&
!datepickerRef?.current?.contains(event?.target)
) {
setOpen(false);
}
};
useEffect(() => {
document.addEventListener("mousedown", handleDocumentClick);
return () => {
document.removeEventListener("mousedown", handleDocumentClick);
};
}, []);
useEffect(() => {
if (validationError) {
toast({
render: ({ onClose }) => (
<HStack
color="#000"
p={4}
backgroundColor="#f56c6cff"
textAlign="center"
fontWeight="normal"
fontSize="16px"
display="flex"
justifyContent="space-between"
minHeight="60px"
width="100%"
>
<Box flex="1" ml="4">
{validationError}
</Box>
<CloseButton color="#000" onClick={() => onClose()} />
</HStack>
),
duration: null,
isClosable: false,
position: "top",
status: "error",
});
}
}, [validationError]);
let borderColor = baseColor;
let bgColor = baseColor;
if (customBorderColor) {
borderColor = disabled
? "#CCCCCC"
: error
? "#ED0000"
: validationError
? "#F56C6C"
: value && !error
? baseColor
: colorSchema === "primary"
? "#ED0000"
: "#F56C6C";
}
if (customBgColor) {
bgColor = disabled
? "#CCCCCC"
: error
? "#F56C6C"
: validationError
? "#F56C6C"
: value && !error
? baseColor
: colorSchema === "primary"
? "#ED0000"
: "#F56C6C";
}
const iconColor = customIconColor ? "#ffffff" : "#fff";
const formattedValue = value ? moment(value).format("YYYY-MM-DD") : "";
return (
<div ref={ref && datepickerRef}>
<DatePicker
selected={value ? new Date(value) : null}
{...(!disabled && {
onBlur: () => {
setOpen(false);
if (validationError) {
setValidationError(
"La date est invalide, elle doit être antérieure à la date de début ou postérieure à la date de fin."
);
}
},
minDate: startDate ? parseDate(startDate) : null,
maxDate: endDate ? parseDate(endDate) : null,
})}
onChange={(date: any) => {
const formattedDate = date ? moment(date).format("YYYY-MM-DD") : "";
const minDate = startDate
? moment(parseDate(startDate)).format("YYYY-MM-DD")
: undefined;
const maxDate = endDate
? moment(parseDate(endDate)).format("YYYY-MM-DD")
: undefined;
if (formattedDate) {
if (
(minDate && formattedDate < minDate) ||
(maxDate && formattedDate > maxDate)
) {
setValidationError(
"La date est invalide, elle doit être antérieure à la date de début ou postérieure à la date de fin."
);
} else {
setValidationError(null);
onChange(formattedDate);
setOpen(false);
}
}
}}
dateFormat="dd-MM-yyyy"
locale={fr}
customInput={
<InputGroup>
<Input
type="date"
bgColor="#fff"
paddingRight="2"
paddingLeft="2"
min={
startDate
? moment(parseDate(startDate)).format("YYYY-MM-DD")
: undefined
}
max={
endDate
? moment(parseDate(endDate)).format("YYYY-MM-DD")
: undefined
}
width={width}
value={formattedValue || value || ""}
borderRightRadius="5px"
placeholder={placeholder || "JJ/MM/AAAA"}
borderColor={borderColor}
_focus={{ outline: "none" }}
textTransform="uppercase"
required={required}
disabled={disabled}
fontSize="13px"
onChange={(e) => {
const inputValue = e.target.value;
onChange(inputValue);
}}
onBlur={(e) => {
const inputValue = e.target.value;
const minDate = startDate
? moment(parseDate(startDate)).format("YYYY-MM-DD")
: undefined;
const maxDate = endDate
? moment(parseDate(endDate)).format("YYYY-MM-DD")
: undefined;
if (inputValue) {
if (
(minDate && inputValue < minDate) ||
(maxDate && inputValue > maxDate)
) {
setValidationError(
"La date est invalide, elle doit être antérieure à la date de début ou postérieure à la date de fin."
);
} else {
setValidationError(null);
onChange(inputValue);
}
}
onChange(inputValue);
}}
/>
<InputRightElement
children={
<img
style={{
fontSize: "15px",
padding: "9px 8px 8px",
}}
src={calendarSvg}
alt="Calendar"
/>
}
color={iconColor}
border={`1px solid ${borderColor}`}
bg={bgColor}
borderRightRadius="5px"
height="100%"
onClick={() => setOpen(!isOpen)}
/>
</InputGroup>
}
open={isOpen}
/>
</div>
);
}
i tried to change the date picker format
dateFormat="dd-MM-yy"
and adding a handleChangeInput to handle the date and parse it correctly .
const inputValue = e.target.value;
if (inputValue.match(/^d{2}-d{2}-d{2}$/)) {
const [day, month, year] = value.split('-');
const fullYear = `20${year}`;
const formattedDate = `${fullYear}-${month}-${day}`;
const parsedDate =formattedDate? moment(parseDate(formattedDate)).format("YYYY-MM-DD"):"";
onChange(parsedDate);
} else {
onChange("");
}