const j = ['立春', '惊蛰', '清明', '立夏', '芒种', '小暑', '立秋', '白露', '寒露', '立冬', '大雪', '小寒'] const News = () => { const formatDate = (date) => { const year = date.getFullYear() const month = date.getMonth() + 1 const day = date.getDate() const hour = date.getHours() const minute = date.getMinutes() const lunarDate = calendar.solar2lunar(year, month, day) const startDate = new Date(lunarDate.date) const endDate = new Date('2023-05-05'); const diffInTime = startDate - endDate const diffInDays = diffInTime / (1000 * 3600 * 24); return `${year}年${month}月${day}日 ${hour}时${minute}分` } return ( <div> <DatePicker onConfirm={handleConfirm} /> </div> ) } 每年的立春,惊蛰,清明,立夏,芒种,小暑,立秋,白露,寒露,立冬,大雪,小寒,这十二节气的阳历日期都不是固定某一个日期,例如立春,有时是阳历2月4日,有时是阳历2月5日。 使用react、es6语法和Hook修改以上代码,使变量endDate里的固定日期改为与startDate接近的上个月节气、当月节气和下个月节气。
时间: 2023-12-03 08:42:20 浏览: 134
以下是修改后的代码:
```
import React, { useState } from 'react';
import DatePicker from 'react-mobile-datepicker';
import calendar from 'chinese-calendar';
const j = ['立春', '惊蛰', '清明', '立夏', '芒种', '小暑', '立秋', '白露', '寒露', '立冬', '大雪', '小寒'];
const News = () => {
const [endDate, setEndDate] = useState(new Date());
const handleConfirm = (date) => {
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
const hour = date.getHours();
const minute = date.getMinutes();
const lunarDate = calendar.solar2lunar(year, month, day);
const lunarMonth = lunarDate.lMonth;
// 获取上个月、当月和下个月的节气
const prevJieQi = j[(lunarMonth + 10) % 12];
const currJieQi = j[lunarMonth % 12];
const nextJieQi = j[(lunarMonth + 2) % 12];
// 计算距离上个月、当月和下个月节气最近的日期
const prevJieQiDate = calendar.getPrevJieQi(year, prevJieQi);
const currJieQiDate = calendar.getThisJieQi(year, currJieQi);
const nextJieQiDate = calendar.getNextJieQi(year, nextJieQi);
// 找到日期最接近的节气
let closestJieQiDate = prevJieQiDate;
let diffInTime = date - prevJieQiDate;
if (nextJieQiDate - date < diffInTime) {
closestJieQiDate = nextJieQiDate;
diffInTime = nextJieQiDate - date;
}
if (currJieQiDate - date < diffInTime) {
closestJieQiDate = currJieQiDate;
}
setEndDate(closestJieQiDate);
}
return (
<div>
<DatePicker
value={endDate}
onConfirm={handleConfirm}
/>
</div>
);
}
```
修改的思路:
1. 使用 `useState` Hook 定义 `endDate` 状态;
2. 在 `handleConfirm` 函数中,先计算当前选择的日期对应的农历日期,并获取当前月份的节气;
3. 然后通过 `calendar` 库提供的方法获取上个月、当月和下个月的节气日期;
4. 最后找到离当前选择日期最接近的节气日期,将其设为新的 `endDate` 值;
5. 在 `DatePicker` 中使用 `value` 属性绑定 `endDate` 状态,并在确认日期时触发 `handleConfirm` 函数。
阅读全文