I'm using the MUI (v5) Datepicker for user birthday input. I've localized it to german language. So the input is DD.MM.YYYY.
Now many german users are using a short year value like DD.MM.YY. But this input would result in wrong values:
Input 05.01.20 gives me Sun Jan 05 0020 00:00:00 GMT+0053. This leads me to two problems:
- How can I 'force' the user to input four digit year values? Typing two digits results in a valid (but useless) date.
- Or (and this would be better) how can I check and handle two digit year values? I would think future values (
80) should get used as1980and18should result in2018.
For me, the second point would be the better solution, so I would have to set the input generally to the format DD.MM.YY and handle those inputs as described. But how do I change the input format of the DatePicker?
import React from 'react'
import AdapterDateFns from '@mui/lab/AdapterDateFns'
import LocalizationProvider from '@mui/lab/LocalizationProvider'
import DatePicker from '@mui/lab/DatePicker'
import deLocale from 'date-fns/locale/de'
import { toDate, isValid } from 'date-fns'
const Component = () => {
const [birthday, setBirthday] = React.useState<Date>(null)
const handleDateChange = (value: any) => {
console.log(isValid(value))
setBirthday(toDate(value))
}
return (
<LocalizationProvider dateAdapter={AdapterDateFns} locale={deLocale}>
<DatePicker
disableFuture
mask="__.__.____"
value={birthday}
onChange={handleDateChange}
renderInput={(params) => (
<TextField {...params} />
)}
/>
</LocalizationProvider>
)
}