思路是这样的
日历分为两个部分,一个是header的星期,一个是body的日期,星期部分从周日开始,周一结束,而日期部分从什么时候开始,取决于本月的一号是周几,知道这些我们就可以开始编写一个日历了
- 首先准备我们需要的数据
- 把十二个月每个月有多少天列出来
- 获取当前月
- 获取今年(获取年份的主要目的是为了判断是否为闰年进而判断2月份有多少天)
- 准备一个数组用来保存日历数据
月份天数list:
monthInDay:[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
当前月month: new Date().getMonth()
今年:year: new Date().getFullYear()
日历数据:calendarBodyList
- 开始时我们要获取上一个月和下一个月
获取上月
let firstMonth = month - 1 < 0 ? 11 : month - 1
获取下月let lastMonth = month + 1 > 11 ? 0 : month + 1)
- 获取当前月的一号是周几,已有今年,当前月,很简单就获取到了
一号是周几:
let onMonday = new Date(year, month, 1).getDay()
- 判断一下闰年, 如果是闰年就改一下二月份的天数
if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) { monthInDay[1] = 29; }
- 已知这个月的一号是周几,根据这个条件能算出需要从上月拿几天填充到calendarBodyList(日历)中,再根据这个月的天数,获取到应该在下个月去前几天填充进calendarBodyList(日历)中, 代码太多我就不贴了,直接放在了下面源码里
- 做完上诉工作,我们已经得到了日历数据,直接在页面中循环就可以了
记录一下
完整代码
let monthInDay = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
let month = new Date().getMonth();
let year = new Date().getFullYear();
let calendarBodyList = [];
calendarBodyList.splice(0);
month = Number(month);
// 上月
let firstMonth = (this.firstMonth = month - 1 < 0 ? 11 : month - 1);
// 下月
let lastMonth = (this.lastMonth = month + 1 > 11 ? 0 : month + 1);
// 这个月的第一天是周几
let onMonday = new Date(year, month, 1).getDay();
// 闰年判断
if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) {
monthInDay[1] = 29;
}
// 取上个月的后几天填充
if (onMonday > 0) {
let firstDays = monthInDay[firstMonth];
let firstArr = [];
for (let i = 0; i < firstDays; i++) {
firstArr.push({
month: firstMonth,
day: i,
year: firstMonth === 11 ? year - 1 : year,
});
}
let firstSplit = firstArr.splice(firstArr.length - onMonday);
calendarBodyList.unshift(...firstSplit);
}
// 填充当月时间
for (let i = 0; i < monthInDay[month]; i++) {
calendarBodyList.push({
month: month,
day: i,
year,
});
}
let nextNum = 0;
if (calendarBodyList.length > 35) {
nextNum = 42 - calendarBodyList.length;
} else {
nextNum = 35 - calendarBodyList.length;
}
// 获取下个月的前几天填充
for (let i = 0; i < nextNum; i++) {
calendarBodyList.push({
month: lastMonth,
day: i,
year: lastMonth === 0 ? year + 1 : year,
});
}
calendarBodyList.forEach((v) => {
v.month += 1;
v.day += 1;
});
console.log(calendarBodyList, "日历初始化");