最近因为某些原因,又在自己的小程序业务组件项目中添加了可左右滑动的日历。
实现思路
获取每月的总天数,使用getDate()
getTotalDays(date) {
let value = new Date(date.year, date.month, 0).getDate()
return value
}
每月1号是周几,使用getDay()
getFirstDayWeek(date) {
return new Date(date.year, date.month - 1, 1).getDay()
}
计算上个月和下个月的残余天数:根据每月的1号是周几计算出上个月的残余天数,根据每月总天数得知上个月的最后一号;日历上显示的日期总个数为7的倍数,由此计算出下个月的残余天数
// 根据当前的天数,计算上月残余天数和下月残余天数
calculateResidualDays(date) {
// 计算上月残余天数,需要知道1号是星期几(个数)且上月最后一天是几号(起始数值)
let last_value = dateUtil.getTotalDays({
year: date.year,
month: date.month - 1
})
for (let i = 0; i < date.firstDayWeek; i++) {
date.list.unshift({
value: this.properties.showRemnantDays ? last_value - i : '',
type: 'last'
})
}
// 计算下月残余天数,需要知道本月显示多少行
let total = Math.floor(date.list.length / 7)
if (date.list.length % 7 > 0) {
++total
}
if (this.properties.fixRow) {
// 设置了每月固定显示6行
total = 6
}
let next_value = total * 7 - date.list.length
// 设置滚动框的高度,设置变化的过度动画
date.swiperHeight = total * 107
for (let i = 1; i <= next_value; i++) {
date.list.push({
value: this.properties.showRemnantDays ? i : '',
type: 'next'
})
}
// 格式化显示的提示信息
this.formatShowTip(date)
},
这样,一个月的相关日期便可以计算出来,其他的相关功能及思路,可见我的github