项目场景:
提示:用于计算月份日期,(当前日期一个月前的日期,当前日期两个月前的日期以此类推,考虑特殊月份了)
问题描述:
提示:下列时间计算适用于,月份计算(此方法是我注册成全局的了)
例如:传入1,返回结果就是当前日期一个月前的日期
export function InRecentMonthsAll(params) {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth() + 1; // 0-11表示1-12月
var day = now.getDate();
var dateObj = {};
dateObj.now = year + '-' + month + '-' + day;
var nowMonthDay = new Date(year, month, 0).getDate(); // 当前月的总天数
let InRecentMonths = ''
if (month - params <= 0) { // 如果是1、2、3月,年数往前推一年
InRecentMonths = new Date((year - 1), (12 - (params - parseInt(month))), 0).getDate(); // X个月前所在月的总天数
if (InRecentMonths < day) { // X个月前所在月的总天数小于现在的天日期
dateObj.last = (year - 1) + '-' + (12 - (params - month)) + '-' + InRecentMonths;
} else {
dateObj.last = (year - 1) + '-' + (12 - (params - month)) + '-' + day;
}
} else {
InRecentMonths = new Date(year, (parseInt(month) - params), 0).getDate(); // X个月前所在月的总天数
if (InRecentMonths < day) { // X个月前所在月的总天数小于现在的天日期
if (day < nowMonthDay) { // 当前天日期小于当前月总天数,2月份比较特殊的月份
dateObj.last = year + '-' + (month - params) + '-' + (InRecentMonths - (nowMonthDay - day));
} else {
dateObj.last = year + '-' + (month - params) + '-' + InRecentMonths;
}
} else {
dateObj.last = year + '-' + (month - params) + '-' + day;
}
}
return dateObj;
}