js、vue处理日期,向前向后N个月,自动处理闰年、月末取n个月后的最后一天

js代码

function getNewDate(date, n) {//date 日期  n 前后相差月份
	let curDate = new Date(date),newDate = new Date(date),diff,remainder //curDate当前日期  newDate计算后日期  diff日期相差月份  remainder n对12的余数
	newDate.setMonth(curDate.getMonth() + n); //设置月份+n
	diff = newDate.getMonth() - curDate.getMonth(); //计算后月与之前月差值
	diff < 0 ? diff += 12: diff; //如果差值小于12 对其+12
	n > 0 ? remainder = n % 12 : remainder = n + 12 * Math.ceil((Math.abs(n) /12 )) //n>0时直接对12取余 n<0时,将其加上 n取绝对值后的年份(向上取整)* 12
	if(diff != remainder){
		return new Date(newDate.setMonth(newDate.getMonth(),0)) //如果diff与remainder不相等,此时的情况是Date.setMonth()方法自动处理了月末日期向后顺延到下个月,将其设置为上个月的最后一天,否则不进行处理
	}
	return newDate;
}

js调用 

getNewDate('2022-05-31',9)

vue代码

getNewDate(date, n) {//date 日期  n 前后相差月份
	let curDate = new Date(date),newDate = new Date(date),diff,remainder //curDate当前日期  newDate计算后日期  diff日期相差月份  remainder n对12的余数
	newDate.setMonth(curDate.getMonth() + n); //设置月份+n
	diff = newDate.getMonth() - curDate.getMonth(); //计算后月与之前月差值
	diff < 0 ? diff += 12: diff; //如果差值小于12 对其+12
	n > 0 ? remainder = n % 12 : remainder = n + 12 * Math.ceil((Math.abs(n) /12 )) //n>0时直接对12取余 n<0时,将其加上 n取绝对值后的年份(向上取整)* 12
	if(diff != remainder){
		return new Date(newDate.setMonth(newDate.getMonth(),0)) //如果diff与remainder不相等,此时的情况是Date.setMonth()方法自动处理了月末日期向后顺延到下个月,将其设置为上个月的最后一天,否则不进行处理
	}
	return newDate;
}

 vue调用

this.getNewDate('2022-05-31',9)

 效果图

PS:向前计算n传负值,向后传正值 

以下更简单粗暴的方法,同样可以达到相同的效果

js代码

function getNewDate(date, n) {//date 日期  n 前后相差月份 向前传负值
	let curDate = new Date(date),newDate = new Date(date)
	newDate.setMonth(curDate.getMonth() + n); //设置月份+n
	if(newDate.getDate() < curDate.getDate()){
		return new Date(newDate.setMonth(newDate.getMonth(),0)) 
	}
	return newDate;
}

vue代码 

getNewDate(date, n) {//date 日期  n 前后相差月份 向前传负值
	let curDate = new Date(date),newDate = new Date(date)
	newDate.setMonth(curDate.getMonth() + n); //设置月份+n
	if(newDate.getDate() < curDate.getDate()){
		return new Date(newDate.setMonth(newDate.getMonth(),0)) 
	}
	return newDate;
}

 

 

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值