Setting "DD/MM/YYYY" format in MUI
Asked Answered
K

4

8

In my MUI form I'm using DatePicker to select dates for departure and return of users. But when I used .toLocaleDateString() it set my dates in mm-dd-yyyy format. But I wanted to set them as dd-mm-yyyy format. For that I've passed 'en-GB' as parameter in .toLocaleDateString(). But in the DatePicker TextField it shows a red border Like this and the pre-defined date (from the state) are also gone. Without the parameter it shows This which is the mm-dd-yyyy format. From the similar previous questions I even tried it through moment package and set the dt variable as moment(new Date()).format("DD/MM/YYYY") but it is still showing red border around the text field. I know this question was asked a lot of times before and I went through all of them and got no solution.

Date picker

const dt = new Date().toLocaleDateString();
  console.log(dt);
  const [formData, setFormData] = useState({
    from: "",
    to: "",
    depart: dt,
    return: dt,
    noOfPassenger: 1,
    tripType: "Return",
  });

   {/* App component  */}
       <div className="dates">
          <LocalizationProvider dateAdapter={AdapterDateFns}>
            <DatePicker
              label="Departure Date"
              disablePast
              onChange={(e) =>
                setFormData({
                  ...formData,
                  depart: e.toLocaleDateString(),
                })
              }
              value={formData.depart}
              renderInput={(params) => <TextField {...params} required />}
            />
          </LocalizationProvider>
        </div>
Kimura answered 30/11, 2021 at 15:4 Comment(2)
Why don't you use TextField like here: codesandbox.io/s/p268w?file=/demo.js or DesktopDatePicker like here: codesandbox.io/s/uuonn?file=/demo.jsIndiscretion
@HlebShypula I did use inputFormat in the datepicker but it didn't work..later I solved this by adding date-fns package and the set the input format in the datepickerKimura
F
8

In my case I used a DateRangePicker, but it's the same across all pickers. Just set the inputFormat like here:

<DateRangePicker
     startText={t`From`}
     endText={t`To`}
     value={dateValue}
     inputFormat="dd.MM.yyyy"
     onChange={(newValue) => {
         setDateValue(newValue);
         console.log(newValue);
     }}
     renderInput={(startProps, endProps) => (
        <React.Fragment>
            <TextField {...startProps} />
            <TextField {...endProps} />
        </React.Fragment>
     )}
/>
Firmin answered 3/3, 2022 at 10:3 Comment(1)
use format instead of inputFormat for MUI version 6.x+Chidester
V
2

I had the same problem and I resolved it by importing this package import 'dayjs/locale/en-gb';

Here is an example:

'use client'; //  skip this if you're not using NextJs

import React, { ReactNode } from 'react';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import 'dayjs/locale/en-gb';

interface Props {
  children: ReactNode;
}

export default function MuiLocalizationProvider({ children }: Props) {
  return (
    <LocalizationProvider dateAdapter={AdapterDayjs} adapterLocale="en-gb">
      {children}
    </LocalizationProvider>
  );
}

After adding the provider, you can now use the date picker like this

const [dueDate, setDueDate] = useState<Dayjs | null>(null);
<DatePicker
  label="Due Date"
  value={dueDate}
  onChange={(newDueDate) => setDueDate(newDueDate)}
/>

For more details https://mui.com/x/react-date-pickers/adapters-locale/

Vitals answered 7/7, 2023 at 10:42 Comment(0)
S
1

Emanuel Avram has already given a good answer. I will just add. The value (date) of the component must have the same format defined internally, so it's no use using "toLocaleString()" without changing the internal format. Use the "inputFormat" property.

// "dd" = "Su", "Mo", ..., "Sa"
// "DD" = "01", "02", ..., "31"
inputFormat="dd/MM/YYYY" // Tu/09/2022
inputFormat="DD/MM/YYYY" // 09/13/2022
<DatePicker
    label="Departure Date"
    inputFormat="DD-MM-YYYY" // 13-09-2022
    onChange={(e) =>
        setFormData({
            ...formData,
            depart: e.toLocaleDateString(),
        })
    }
    value={formData.depart}
    renderInput={(params) => <TextField {...params} required />}
/>
Stetson answered 13/9, 2022 at 14:50 Comment(0)
R
0

Just add format="DD/MM/YYYY" or format ="DD-MM-YYYY" as one of the props to the DatePicker.

Retardation answered 16/7 at 9:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.