Skip to content

Instantly share code, notes, and snippets.

@libo1106
Created August 30, 2018 12:07
Show Gist options
  • Save libo1106/15045e39be7e6415f2e5c7ca87059df2 to your computer and use it in GitHub Desktop.
Save libo1106/15045e39be7e6415f2e5c7ca87059df2 to your computer and use it in GitHub Desktop.
获取指定月份的日历
/**
* 计算目标月份的日历,返回按星期组合的二维数组
* @param year
* @param month
* @returns {Array|*}
*/
function getDays(year, month) {
// 目标月份第一天
let firstDay = moment(`${year}-${month}`, 'YYYY-MM').startOf('month');
// 目标月份最后一天
let lastDay = moment(`${year}-${month}`, 'YYYY-MM').endOf('month');
// 目标月份总天数
const maxDays = moment(`${year}-${month}`, 'YYYY-MM').daysInMonth();
let daysArr = [];
let i = 1;
for (i; i <= maxDays; i++) {
daysArr.push(i);
}
// 补充第一行内容
while (firstDay.day() !== 0) {
firstDay = firstDay.subtract(1, 'days');
daysArr.unshift(firstDay.format('D'));
}
// 补充最后一行内容
while (lastDay.day() !== 6) {
lastDay = lastDay.add(1, 'days');
daysArr.push(lastDay.format('D'));
}
return _.chunk(daysArr, 7);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment