效果
可以切换月份
//初始化当月
initDate:function(){
let that =this;
let currentDate=new Date();
let year=currentDate.getFullYear();
let month = currentDate.getMonth()+1;
$('#yearTxt').text(year+'年'+(month)+'月');
let monthFirst=year+'-'+(month)+'-'+'1';
this.getDateShow(monthFirst,month);
//点击上一月
$(document).on('click','[f="up_month"]',function(){
let upDate='';
//如果是1月
if(month==1){
year=year-1;
month=12;
upDate=year+'-'+month+'-1';
}else{
//上一月 月份-1
month= month-1;
upDate=year+'-'+(month)+'-1';
}
that.getDateShow(upDate,month);
$('#yearTxt').text(year+'年'+(month)+'月');
})
//点击下一月
$(document).on('click','[f="next_month"]',function(){
let nextDate='';
//如果是12月
if(month==12){
year=year+1;
month=1;
nextDate=year+'-'+month+'-1';
}else{
//下一月月份+1
month= month+1;
nextDate=year+'-'+(month)+'-1';
}
that.getDateShow(nextDate,month);
$('#yearTxt').text(year+'年'+(month)+'月');
})
},
//渲染计算,monthFirst月第一天的日期,month月
getDateShow:function(monthFirst,month){
let dayTime = 1000*60*60*24;//一天的毫秒数
let dayLengt=42;//表格需要展示的天数
let monthFirstTime=new Date(monthFirst).getTime();//本月第一天时间戳
let firstWeek=new Date(monthFirst).getDay();//获取当月第一天星期几
if(firstWeek==0){ //星期数为0等于星期天
firstWeek=7;
}
//使用当月第一天减去星期数获取第一天开始日期
let firstDay=new Date(monthFirstTime - ((firstWeek-1)*dayTime)).getTime();
//获取最后一个日期
let lastDay=new Date(firstDay+(dayLengt*dayTime)).getTime();
let showDate='';
for(let i= firstDay; i< lastDay; i+=dayTime){
let showCurrnetDate=new Date(i);
console.log(showCurrnetDate.getFullYear()+'年'+showCurrnetDate.getMonth()+'月'+showCurrnetDate.getDate()+'日');
if(showCurrnetDate.getMonth()+1 != month){ //不是本月颜色为灰色
showDate+=`<span class="w14per lh30 color_9 mb5 t_center">${showCurrnetDate.getDate()}</span>`
}else{
showDate+=`<span class="w14per lh30 color_0 mb5 t_center">${showCurrnetDate.getDate()}</span>`
}
}
$('#daylist').html(showDate);
},