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
大家讲道理2017-05-19 10:26:49
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:
Construct a 6*7 array daysArr
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)
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)
Calculate the values of other elements of daysArr based on daysArr[0][0]
滿天的星座2017-05-19 10:26:49
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);
ringa_lee2017-05-19 10:26:49
let result = [...Array(42).keys()].reduce((acc, val) => {
acc.push(moment().add(val, 'day').format('YYYY/MM/DD'));
return acc;
}, []);