关于JS的setMonth方法
例子:targetDate = 2022/7/31
需求:取到目标日期前1个月的日期
理想结果:2022/6/30
已下为示例代码:
var targetDate = new Date("2022/7/31");
targetDate.setMonth(targetDate.getMonth() - 1);
console.log("targetDate",targetDate);
js运行结果:2022/7/1
如何解决这个问题而得到目标值?
探究其中的原因,是因为js只是将月份减去或加上对应的月份,对于日期并没有做更改。
即通过setMonth之后,得到的日期为 2022/6/31,导致日期数据溢出,自动转为 2022/7/1。
查看其它博主建议解决方法,是setMonth(targetDate.getMonth() - 1,1);这样可以保证得到的月份是对的,但是日期不是我需要的。
以下为我的解决方案,将多出来的日期,强行减掉
/**
* @param num - 为需要增加或者减去的月份数
* @return {Date}
*/
Date.prototype.setDateMonth = function (num) {
if (isNaN(num)) return NaN;
var targetDate = this;
var cy_mm = num % 12;
var origin_mm = targetDate.getMonth();
targetDate.setMonth(Number(targetDate.getMonth()) + Number(num));
while(true){
if (targetDate.getMonth() - origin_mm == cy_mm) break;
if (origin_mm - targetDate.getMonth() == cy_mm) break;
if (origin_mm - targetDate.getMonth() == -12 - cy_mm) break;
if (origin_mm - targetDate.getMonth() == 12 - cy_mm) break;
if (targetDate.getMonth() - origin_mm == 12 - cy_mm) break;
if (targetDate.getMonth() - origin_mm == -12 - cy_mm) break;
targetDate.setDate(targetDate.getDate() - 1);
}
return targetDate;
}
var targetDate = new Date("2022/7/31");
targetDate.setDateMonth(- 1);
console.log("targetDate",targetDate);
js运行结果:2022/6/30