inputFormat of material ui v5 Datepicker

Viewed 35

I am using material ui v5 Datepicker, trying to figure out what is the input format for a date like, Saturday, September 24th 2022. In v4, it is "dddd, MMMM Do YYYY", but it does not work for v5. I figured in v4 we were using MomentUtils, in v5 we switched to AdapterDayjs? Any suggestion? I wonder how do find out all the valid input formats.

2 Answers

You need to extend DayJs instance with advancedFormat and pass this new instance to the LocalizationProvider as dateLibInstance prop like this:

import * as React from "react";
import DayJsInstance, { Dayjs } from "dayjs";
import advancedFormat from "dayjs/plugin/advancedFormat";
import TextField from "@mui/material/TextField";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
import { DatePicker } from "@mui/x-date-pickers/DatePicker";

DayJsInstance.extend(advancedFormat);

export default function BasicDatePicker() {
  const [value, setValue] = React.useState<Dayjs | null>(null);

  return (
    <LocalizationProvider
      dateAdapter={AdapterDayjs}
      dateLibInstance={DayJsInstance}
    >
      <DatePicker
        inputFormat="dddd, MMMM Do YYYY"
        label="Basic example"
        value={value}
        onChange={(newValue) => {
          setValue(newValue);
        }}
        renderInput={(params) => (
          <TextField style={{ width: 400 }} {...params} />
        )}
      />
    </LocalizationProvider>
  );
}

You can take a look at this sandbox for a live working example of this solution.

According to the doc, you could choose any adapter that you want, in the list of

  • date-fns
  • day.js
  • luxon
  • moment.js

To use moment.js, you need to import its adapter and pass to the LocalizationProvider

import { AdapterMoment } from '@mui/x-date-pickers/AdapterMoment';

function ParentComponent({ children }) {
  return (
    <LocalizationProvider dateAdapter={AdapterDayjs}>
      {children}
    </LocalizationProvider>
  );
}

Also, we could see that MUI uses @date-io as the adapter. So if you want to check for the valid input formats, go to the relevant @date-io package, check for the version of date-library in the dependencies, and from that version, go to the date-library doc to see the related format.

For example, if you use date-fns, you would go to @date-io/date-fns repository, open package.json, and notice the version of date-fns in dependencies (here is 2.16). After that, you would find the doc with the related version found previously, to check for the supported format.

  "devDependencies": {
    "date-fns": "2.16.1",
    "rollup": "^2.0.2",
    "typescript": "^3.7.2"
  },
Related