IDE:idea
系统:WIN10 20H2
前端:elementUI
/**
* 设置本地月份
* @param date 处理前日期
* @param number 需要处理的月份(正负皆可,例如:+1就是加一个月)
* @returns {Date|*}
*/
localSetMonth(date, number) {
const currentMonth = date.getMonth();
// 获取传入月份的最大天数
let tempDate1 = new Date();
tempDate1.setDate(1);
tempDate1.setMonth(currentMonth + 1);
tempDate1 = new Date(tempDate1.getFullYear(), tempDate1.getMonth(), 0);
const currentMonthMaxDate = tempDate1.getDate();
// 获取处理后月份的最大天数
let tempDate2 = new Date();
tempDate2.setDate(1);
tempDate2.setMonth(currentMonth + number + 1);
tempDate2 = new Date(tempDate2.getFullYear(), tempDate2.getMonth(), 0);
const afterHandlerMonthMaxDate = tempDate2.getDate();
// 判断两个日期是否相等(就一定不会出现跳月的情况)
if (currentMonthMaxDate === afterHandlerMonthMaxDate) {
date.setMonth(date.getMonth() + number);
return date;
}
// 如果两个月份不相等,则判断传入日期是否在月底,如果是月底则目标日期也设置为月底
if (date.getDate() === currentMonthMaxDate) {
tempDate2.setDate(afterHandlerMonthMaxDate);
return tempDate2;
}
// 判断闰年
if (date.getDate() >= afterHandlerMonthMaxDate) {
tempDate2.setDate(afterHandlerMonthMaxDate);
return tempDate2;
}
date.setMonth(date.getMonth() + number);
return date;
}