首页 > 解决方案 > 根据日期名称获取整月日期的函数

问题描述

我正在尝试根据用户选择的日期禁用一个月中的所有日期,例如:如果用户选择星期一,我需要禁用所有星期一。

所以我有这个函数,它需要 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”之后的日期,即上周日期丢失。

标签: javascriptreactjsfunction

解决方案


这将输出您当月的所有禁用天数

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)

推荐阅读