buzz
buzz

Reputation: 1106

Setting "DD/MM/YYYY" format in MUI

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>

Upvotes: 8

Views: 25197

Answers (4)

Aishwarya Khatri
Aishwarya Khatri

Reputation: 11

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

Upvotes: 1

Bablu Ahmed
Bablu Ahmed

Reputation: 5020

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/

Upvotes: 2

Dhenyson Jhean
Dhenyson Jhean

Reputation: 824

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 />}
/>

Upvotes: 1

Ceatry
Ceatry

Reputation: 97

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>
     )}
/>

Upvotes: 8

Related Questions