javascript根据当前日期获取给定天数的日历表

根据当前日期获取给定天数的日历表

思路:
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,设置每月一号对应星期的偏移量

根据返回数据排版效果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值