如何使用javascript在日历中管理30天和2月的月份

时间:2020-01-31 09:43:52

标签: javascript reactjs calendar leap-year

这是在组件加载时调用的函数。该函数以31天返回所有月份。 2月和30天的月份也将返回31天。如何将月份的天数限制为30天,将2月限制为leap年的28天或29天。

const getCalendarCells = (date, items) => {

  var cells = [];
  try {
    if (items === undefined || items === null) {
      items = {};
    }
    /*----- Finding start of the month -----*/
    var start = new Date();
    start.setMonth(date.getMonth());
    start.setFullYear(date.getFullYear());
    start.setDate(1);
    /*----- Finding start of the calendar date -----*/
    while (start.getDay() != 0) {
      start.setDate(start.getDate() - 1);
    }
    /*----- Finding all calendar day of weeks headers -----*/
    cells.push(['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT']);
    /*----- Finding all calendar cells -----*/
    var weekCells = [];
    for (var i = 0; i <= 42; i++) {
      if (i > 0 && i % 7 === 0) {
        cells.push(weekCells);
        weekCells = [];
      }
      if (i === 42) {
        break;
      } else {
        var type = (start.getMonth() === date.getMonth() && start.getFullYear() === date.getFullYear()) ? 'THIS' : 'OTHER';
        weekCells.push({
          data: (type === 'THIS' ? items[start.getDate().toString()] : {}),
          value: new Date(start.toString()).getDate(),
          type: type
        });
        start.setDate(start.getDate() + 1);
      }
    }
    console.log(cells)
    setReport(cells);

  } catch (ex) {}

}

0 个答案:

没有答案