Is there any way to auto date format using Keyboarddatepicker

155 views Asked by At

We are using material ui Keyboarddatepicker, and we have set date format using props in react format=DD/MMM/YYYY so date will be set like "10/12/2020".

It is working perfectly when we select date from datepicker. But we are having problems when we enter the date manually or type it with another date format, like dd/mm/yyyy, or when we enter a numeric value. Then it should be set based on typed value, like when we type 10122000, then it should still be set in date format like "10/12/2020".

How can I convert all date input formats into our required date format?

<MuiPickersUtilsProvider libInstance={moment} utils={MomentUtils}>
  <KeyboardDatePicker autoOk={true} value={selectedDate} format="DD/MMM/YYYY" onChange={handleDateChange} />
</MuiPickersUtilsProvider>
1

There are 1 answers

11
underflow On

You can try something like this

function transformDate(inputString) {
  const inputDateUS = new Date(inputString);
  const inputDateFr = new Date(inputDateUS.getFullYear(), inputDateUS.getDate() - 1, inputDateUS.getMonth() + 1)
  const formattedDate = inputDateFr.toLocaleString('default', { day: "numeric", month: "short", year: "numeric" });
  return formattedDate.split(" ").join("/");
}


// 10/01/2020 is transformed correctly
console.log(transformDate("10/01/2020"));

// 10-01-2020 is transformed correctly
console.log(transformDate("10-01-2020"));

As you can see, whatever the European format date that you enter, the funtion will output the format that you want, that is DD/MMM/YYYY.

Now all you have to do is get the input of the Date Picker, pass it to the function, then display the output (give the result back to the date picker).

In your case, replace value={selectedDate} with value={transformDate(selectedDate)}

Hope it helps