我正在努力解决以下问题:我正在使用CCD_ 1,并且我将所选日期格式化为";YYYY-MM-DD
";。我的代码如下:
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;
组件如下:
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;
我使用的是文档中的示例,但我无法根据需要格式化所选日期(YYYY-MM-DD
(。formatDate方法不起作用。我认为必须以另一种方式来实施。也许有使用此软件包经验的人可以帮助我解决这个问题。
日期、月份和年份的值分别为12001。所有字符串。
试试这个函数,它可能会对你有所帮助!
const formatDate = (date) => {
date = new Date(date);
if(date == 'Invalid Date') return date;
let month = date.getMonth();
let day = date.getDate();
return `${date.getFullYear()}-${day<10?'0':''}${day}-${month<10?'0':''}${month+1}`;
}
export default formatDate;