获取日历月份数据

29 阅读1分钟

工作修改bug的时候发现代码中的获取月份日历数据有问题,于是自己写了一个(借助momentjs),仅为记录:

const moment = require('moment');

function getCalendarListByYearAndMonth(year, month) {
  const firstDay = `${year}-${month}-1`;
  // 当前年份月份的一号是周几
  const weekDay = moment(firstDay).day();
  // 计算当前月份日历第一个日期
  const startDate = moment(firstDay).subtract(weekDay, 'days');
  // weekDay为0表示周日 五行即可展示一个月数据
  return [...Array(weekDay ? 42 : 35).keys()].map((num) => {
    return moment(startDate).add(num, 'days').format('YYYY-MM-DD');
  });
}

console.log(getCalendarListByYearAndMonth(2023, 1));
// [
//   '2023-01-01', '2023-01-02', '2023-01-03',
//   '2023-01-04', '2023-01-05', '2023-01-06',
//   '2023-01-07', '2023-01-08', '2023-01-09',
//   '2023-01-10', '2023-01-11', '2023-01-12',
//   '2023-01-13', '2023-01-14', '2023-01-15',
//   '2023-01-16', '2023-01-17', '2023-01-18',
//   '2023-01-19', '2023-01-20', '2023-01-21',
//   '2023-01-22', '2023-01-23', '2023-01-24',
//   '2023-01-25', '2023-01-26', '2023-01-27',
//   '2023-01-28', '2023-01-29', '2023-01-30',
//   '2023-01-31', '2023-02-01', '2023-02-02',
//   '2023-02-03', '2023-02-04'
// ]

如需特殊的数据结构,可以在此基础上进行加工