Dwix
Dwix

Reputation: 1257

Get React DatePicker date value in onChange

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.

Upvotes: 1

Views: 31629

Answers (2)

TheTisiboth
TheTisiboth

Reputation: 1651

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")

Upvotes: 3

Aniruddh Thakor
Aniruddh Thakor

Reputation: 1616

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

Upvotes: 5

Related Questions