javascript - 根据日期名称获取整月日期的函数
问题描述
我正在尝试根据用户选择的日期禁用一个月中的所有日期,例如:如果用户选择星期一,我需要禁用所有星期一。
所以我有这个函数,它需要 3 个参数(月、年和禁用日数组)。看起来它在工作,直到我禁用了数组
[
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
]
例如:我有这个参数,月份是 3,年份是 2021,天数如上数组。
const getDaysInMonth = (month, year, days) => {
let pivot = moment().month(month).year(year).startOf("month");
const end = moment().month(month).year(year).endOf("month");
let dates = {};
const disabled = { disabled: true, disableTouchEvent: true };
while (moment(pivot).isBefore(end)) {
days.forEach((day) => {
dates[pivot.day(day).format("YYYY-MM-DD")] = disabled;
});
pivot.add(7, "days");
}
console.log("before return is", dates);
return dates;
};
使用此功能,我没有得到“24th sataturday”之后的日期,即上周日期丢失。
解决方案
这将输出您当月的所有禁用天数
const getDaysInMonth = (month, year, days) => {
const endDay = moment()
.year(year)
.month(month - 1)
.endOf("month")
return Array.from({ length: 31 }).reduce((acc, _, i) => {
const date = moment()
.month(month - 1)
.year(year)
.startOf("month")
.add(i, "day")
const day = date.format("dddd")
if (days.includes(day) && date.isSameOrBefore(endDay))
acc = [...acc, date.format("YYYY-MM-DD")]
return acc
}, [])
}
const result = getDaysInMonth(4, 2021, [
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
])
console.log(result)
推荐阅读
- java - 使用地图作为 responseContainer 的 @ApiResponse 上的 Swagger API 文档不起作用
- android - 带有架构导航组件的底部导航片段的动画
- r - R - f_num,但带逗号
- c++ - 如何在 C++ 中检查模板类中的类型?
- google-cloud-platform - 将 gcloud sql 备份恢复到另一个实例会引发 400 错误
- python - 在纸牌游戏中需要有关此功能的建议
- flutter - 我的 Flutter 网页的滚动正文出现问题
- r - 我将此数据集导入到 RStudio,但它为 NULL
- python - Python:Spacy NER 和内存消耗
- build.gradle - 将 ArchiveName 传递给 gradle 中的 UploadArchives