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
歡迎選擇我的課程,讓我們一起見證您的進(jìn)步~~
There seems to be no method to directly generate a calendar in the moment.js API
monthDay(date) {
const daysArr = [[], [], [], [], [], []]; // 6*7的日歷數(shù)組
const currentWeekday = moment(date).date(1).weekday(); // 獲取當(dāng)月1日為星期幾
const lastMonthDays = moment(date).subtract(1, 'month').daysInMonth(); // 獲取上月天數(shù)
const currentMonthDays = moment(date).daysInMonth(); // 獲取當(dāng)月天數(shù)
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能識(shí)別的格式
...
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]
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;
}, []);