获取每个月的天数
普通的写法
//计算传入月份有多少天
getDayNum(month, year) {
let dayNum = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) {
dayNum[1] = 29;
}
return dayNum[month - 1];
}
简单的写法
new Date(year,month,0)
// 例如 2018 年12月份的天数
new Date(2018,12,0)
原理:js中month是一个特殊的存在,她是比当前月份小1的一个数,例如
2018-11-01 打印出来的getMonth是10
(2018,11,0) 11表示的是12月,12月0日其实就是11月最后一天,11月最后一天就是11月的天数。
定位每个月的第一天
我使用的是[‘日’, ‘一’, ‘二’, ‘三’, ‘四’, ‘五’, ‘六’]这样的格式
如何得到每一天对应星期几,方法是getDay();
周日是0,周一是1.。。。。。
所以拿到每个月第一天对应的数字,然后前面空几格,这样在页面上展示就是对应的关系了。
代码如下
// 每个月的第一天 用null表示,例如1号是周三,则前面放3个null,周日是0,前面放0个null
getMonthList (year, month) {
let monthlist = []
let count = this.getMonthDays(year, month)
let nullcount = new Date(year, month - 1, 1).getDay()
for (var j = 0; j < nullcount; j++) {
monthlist.push({day: null, active: false})
}
for (var i = 1; i <= count; i++) {
monthlist.push({day: i, active: true})
}
return monthlist
},
未完待续,想到什么再记录