1

The date is presented in the right format (31/08/21), but onChange sets the startDate to something like this:

Tue Aug 31 2021 21:29:17 GMT+0200 (Mitteleuropäische Sommerzeit)

How can I save the format I display?

import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";

export default function Bodyweight() {
  
const [startDate, setStartDate] = useState(new Date());

return(
<div>
  <DatePicker
          dateFormat="dd/MM/yy"
          selected={startDate}
          onChange={(date) => setStartDate(date)}
        />
</div>
)}
AlexJanow
  • 67
  • 2
  • 10

3 Answers3

0

Your DatePicker component accepts date in Tue Aug 31 2021 21:29:17 GMT+0200 (Mitteleuropäische Sommerzeit) format.

And it also returns the date in same format.

In order to convert the date in required format, you have few options.

  1. If DatePicker is your own component, check its implementation and modify the code, so that it returns the date in required format.

  2. If option 1 is not an option, then manually convert the date in required format. Note that you may need a third variable to store the formatted date, as your DatePicker components accepts an actual date object not string.

Refer this link to convert date in req format. Format JavaScript date as yyyy-mm-dd

Rahul
  • 5,594
  • 7
  • 38
  • 92
0

Just use new Date().toLocaleDateString() in your initial state set, i.e,

const [startDate, setStartDate] = useState(new Date().toLocaleDateString());

I'm answering according to my understanding, if this is not the solution you are looking for, please do rectify in comments

0

A bit late to the party but you could try something like this onChange={(date:Date) => setStartDate(date)}

gpap
  • 2,394
  • 2
  • 9
  • 8