javascript - Use moment.js to generate the data structure of the calendar for the specified month
天蓬老师
天蓬老师 2017-05-19 10:24:49
0
3
1297

Please give me a best practice. I’m not familiar with moment (I’ve been looking at the API for a day and I understand the basics). I don’t want to take the wrong path. Please give me the final data structure , such as [[ 26,27,28,1,2,3,4], [], [], ...]

Thank you, woohaha

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(3)
大家讲道理

There seems to be no method to directly generate a calendar in the moment.js API

  monthDay(date) {
    const daysArr = [[], [], [], [], [], []]; // 6*7的日历数组
    const currentWeekday = moment(date).date(1).weekday(); // 获取当月1日为星期几
    const lastMonthDays = moment(date).subtract(1, 'month').daysInMonth(); // 获取上月天数
    const currentMonthDays = moment(date).daysInMonth(); // 获取当月天数
    const getDay = day => (day <= lastMonthDays ? day : (day <= (lastMonthDays + currentMonthDays)) ? day - lastMonthDays : day - (lastMonthDays + currentMonthDays)); // 日期处理
    for (let i = 0; i < 7; i += 1) {
      let virtualDay = (lastMonthDays - currentWeekday) + i;
      for (let j = 0; j < 6; j += 1) {
        daysArr[j][i] = getDay(virtualDay + (j * 7));
      }
    }
    console.table(daysArr);
  }
  ...
  monthDay(date); //date格式为moment能识别的格式
  ...

General idea:

  1. Construct a 6*7 array daysArr

  2. Get the number of days in the previous month, the number of days in this month, and the day of the week corresponding to the first of this month (0 means Monday)

  3. Then calculate the corresponding date daysArr[0][0] (the number of days in the previous month - the week corresponding to the first of this month)

  4. Calculate the values ​​of other elements of daysArr based on daysArr[0][0]

滿天的星座

One-dimensional date array can be thought of as follows:

const dates = []
for(let i = 0; i < 42; i+=1) {
  const startDate = moment('2017-05-20').date(1);
  dates[i] = startDate.weekday(i).date();
};
console.log(dates);
左手右手慢动作
let result = [...Array(42).keys()].reduce((acc, val) => {
    acc.push(moment().add(val, 'day').format('YYYY/MM/DD'));
    return acc;
}, []);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template