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); //设置月份+ndiff = newDate.getMonth() - curDate.getMonth(); //计算后月与之前月差值diff < 0 ? diff += 12: diff; //如果差值小于12 对其+12n > 0 ? remainder = n % 12 : remainder = n + 12 * Math.ceil((Math.abs(n) /12 )) //n>0时直接对12取余 n<0时,将其加上 n取绝对值后的年份(向上取整)* 12if(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); //设置月份+ndiff = newDate.getMonth() - curDate.getMonth(); //计算后月与之前月差值diff < 0 ? diff += 12: diff; //如果差值小于12 对其+12n > 0 ? remainder = n % 12 : remainder = n + 12 * Math.ceil((Math.abs(n) /12 )) //n>0时直接对12取余 n<0时,将其加上 n取绝对值后的年份(向上取整)* 12if(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); //设置月份+nif(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); //设置月份+nif(newDate.getDate() < curDate.getDate()){return new Date(newDate.setMonth(newDate.getMonth(),0)) }return newDate;
}

 

 


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部