I'm struggling with the following problem:
I'm using react-dropdown-date
and I have an issue formatting the selected date to format "YYYY-MM-DD
".
My code is the following:
formatDate.js
// formats date to 'yyyy-mm-dd'
const formatDate = (day, month, year) => {
var d = new Date(day, month, year),
month = "" + (d.getMonth() + 1),
day = "" + d.getDate(),
year = d.getFullYear();
if (month.length < 2) {
month = '0' + month;
}
if (day.length < 2) {
day = '0' + day;
}
return [year, month, day].join('-');
}
export default formatDate;
and the component is the following:
import React, { useState, useEffect } from "react";
import { YearPicker, MonthPicker, DayPicker } from "react-dropdown-date";
import formatDate from "./formatDate";
import "./styles.scss";
const DOB = () => {
const [date, setDate] = useState({ year: null, month: null, day: null });
const [selectedDate, setSelectedDate] = useState(null);
// useEffect(() => {
// setSelectedDate(formatDate(date.day, date.month, date.year));
// }, [date]);
console.log('selectedDate', selectedDate);
console.log(date.day, date.month, date.year);
return (
<div className="dob__main-container">
<div>
<DayPicker
classes={"dob__day"}
defaultValue={"DD"}
year={date.year} // mandatory
month={date.month} // mandatory
endYearGiven // mandatory if end={} is given in YearPicker
required={true} // default is false
value={date.day} // mandatory
onChange={day => {
// mandatory
setDate({ day });
console.log(day);
}}
id={"day"}
name={"day"}
/>
<MonthPicker
classes={"dob__month"}
defaultValue={"MM"}
endYearGiven // mandatory if end={} is given in YearPicker
year={date.year} // mandatory
required={true} // default is false
value={date.month} // mandatory
onChange={month => {
// mandatory
setDate({ month });
console.log(month);
}}
id={"month"}
name={"month"}
/>
<YearPicker
classes={"dob__year"}
defaultValue={"YYYY"}
start={1901} // default is 1900
end={new Date().getFullYear()} // default is current year
reverse // default is ASCENDING
required={true} // default is false
value={date.year} // mandatory
onChange={year => {
// mandatory
setDate({ year });
console.log(year);
}}
id={"year"}
name={"year"}
/>
</div>
</div>
);
};
export default DOB;
I'm using the example from documentation, but I can't get to format the selected date as I need to (YYYY-MM-DD
). The formatDate method is not working. I think it must be implemented in another way.
Maybe someone with experience using this package can help me solve this issue.
The values are 1, 1, 2001 for day, month, year. All strings.