1

I'm using react-datepicker, and I'm unable to get the actual date in onChange.

This is my component :

import DatePicker from "react-datepicker";

const DatePick = () => {
  return (
    <DatePicker
      locale="fr"
      dateFormat="dd/MM/yyyy"
      onChange={(date) => {
        console.log(date);
      }}
    />
  );
};

export default DatePick;

In console.log I'm getting this kind of string Thu Dec 09 2021 00:00:00 GMT+0100 (heure normale d’Europe centrale).

I need to get the date as dd-MM-yyyy in onChange or a date that I can format and use later in a form and submit its value.

Dwix
  • 1,139
  • 3
  • 20
  • 45

2 Answers2

5

Use Below code , it will work like a charm

const [Cdate, setDate] = useState(new Date().toLocaleDateString('fr-FR'));
return (
 <>
  <DatePicker
    dateFormat="dd/MM/yyyy"
    value={Cdate}
    onChange={(date) => {
      const d = new Date(date).toLocaleDateString('fr-FR');
      console.log(d);
      setDate(d);
    }}
  />
 </>
);

stackblitz link: https://stackblitz.com/edit/react-nov8it?file=src/App.js

Aniruddh Thakor
  • 1,396
  • 2
  • 9
  • 18
3

You can use the Date object, to format the date as you would like. For instance :

onChange={(date) => {
    const dateString = new Date(date).toLocaleDateString()
    console.log(dateString)
  }}

You will then get the date formated to your locale time zone. However, if you specified a different format in your DatePicker from your local timezone format, then you can specify it as a parameter for toLocaleDateString:

new Date(date).toLocaleDateString("fr-FR")
TheTisiboth
  • 1,431
  • 1
  • 6
  • 13