根据当前日期获取给定天数的日历表
思路:
1、获取当前日期
2、获取当月的第一天日期
3、从当月第一天开始,根据给定天数循环遍历,小于当前日期时,设置不可用状态;大于等于当前日期时,设置可用状态,同时更改遍历条件
4、根据最后一天所在月份,遍历出该月剩余日期,设置不可用状态
5、返回日历数组
示例代码
/*
* 根据当前日期获取给定天数的日历表
* days: 给定天数
*/
function calCalender(days){
let currentDate = new Date(), calender = [], tempDate, y,m,d, tempY, tempM, tempD, tempStr, len, week;
// 获取当前日期年月日
y = parseInt(currentDate.getFullYear());
m = (currentDate.getMonth()+1)>9?(currentDate.getMonth()+1):'0'+(currentDate.getMonth()+1);
m = parseInt(m);
d = parseInt(currentDate.getDate());
// 获取当前月份第一天日期
tempDate = currentDate.setDate(1);
tempDate = new Date(tempDate);
// 从当前月第一天开始,根据给定天数遍历,每循环一次日期加一
for(let i =0; i<= days;){
tempY = tempDate.getFullYear();
tempM = (tempDate.getMonth()+1)>9?(tempDate.getMonth()+1):'0'+(tempDate.getMonth()+1);
tempM = parseInt(tempM);
tempD = parseInt(tempDate.getDate());
tempStr = tempY + '年' + tempM +'月';
// 根据临时日期于当前日期比较,设置日期的状态
if(tempY > y){ // 跨年
if(!calender[tempStr]){
calender[tempStr] = [];
len = 0
}else{
len = calender[tempStr].length;
}
calender[tempStr][len] = {
d: tempD,
w: week,
status: true,
checked: false
}
++i
}else if(tempY === y){ // 同年
if(tempM === m){ // 同月
if(tempD <= d){ // 同月小于等于当前日期
if(!calender[tempStr]){
calender[tempStr] = [];
}
len = calender[tempStr].length;
calender[tempStr][len] = {
d: tempD,
w: week,
status: false
}
}else{ // 同月大于当前日期
len = calender[tempStr].length;
calender[tempStr][len] = {
d: tempD,
w: week,
status: true,
checked: false
}
++i
}
}else{ // 跨月
if(!calender[tempStr]){
calender[tempStr] = [];
len = 0
}else{
len = calender[tempStr].length;
}
calender[tempStr][len] = {
d: tempD,
w: week,
status: true,
checked: false
}
++i
}
}
// 日期加一
tempDate = tempDate.setDate(tempDate.getDate()+1);
tempDate = new Date(tempDate);
}
// 根据最后一天月份,遍历改月剩余日期,状态设为false
let tempDate_m = tempM;
while(tempDate_m == tempM){
len = calender[tempStr].length;
calender[tempStr][len] = {
d: tempD,
w: week,
status: false,
checked: false
};
tempDate = tempDate.setDate(tempDate.getDate()+1);
tempDate = new Date(tempDate);
tempY = tempDate.getFullYear();
tempM = (tempDate.getMonth()+1)>9?(tempDate.getMonth()+1):'0'+(tempDate.getMonth()+1);
tempM = parseInt(tempM);
tempD = parseInt(tempDate.getDate());
week = tempDate.getDay();
tempStr = tempY + '年' + tempM +'月';
}
return calender;
}
返回数据格式
注:w记录星期值,可用来在日历上根据w,设置每月一号对应星期的偏移量
根据返回数据排版效果