1.获取n个月之前
/**
* @author: yaoxueke
* @description: 获取几个月前的日
* @param date 日期
* @param num 几个月
* @return {*}
*/
const numAfterDate = (date: any, num: number) => {
var arr: any = date.split('-');
var year: any = arr[0]; //获取当前日期的年份
var month: any = arr[1]; //获取当前日期的月份
var day: any = arr[2]; //获取当前日期的日
var days: any = new Date(year, month, 0);
days = days.getDate(); //获取当前日期中月的天数
var year2: any = year;
var month2: any = parseInt(month) - num;
if (month2 == 0) {
year2 = parseInt(year2) - 1;
month2 = 12;
}
var day2: any = day;
var days2: any = new Date(year2, month2, 0);
days2 = days2.getDate();
if (day2 > days2) {
day2 = days2;
}
if (month2 < 10) {
month2 = '0' + month2;
}
var t2 = year2 + '-' + month2 + '-' + day2;
console.log(t2, '获取日期')
return t2;
}
2.获取n个月之后
/**
* 获取下一个月
*
* @date 格式为yyyy-mm-dd的日期,如:2014-01-25
* @num 几个月
*/
function getNextMonth(date,num) {
var arr = date.split('-');
var year = arr[0]; //获取当前日期的年份
var month = arr[1]; //获取当前日期的月份
var day = arr[2]; //获取当前日期的日
var days = new Date(year, month, 0);
days = days.getDate(); //获取当前日期中的月的天数
var year2 = year;
var month2 = parseInt(month) + num;
if (month2 == 13) {
year2 = parseInt(year2) + 1;
month2 = 1;
}
var day2 = day;
var days2 = new Date(year2, month2, 0);
days2 = days2.getDate();
if (day2 > days2) {
day2 = days2;
}
if (month2 < 10) {
month2 = '0' + month2;
}
var t2 = year2 + '-' + month2 + '-' + day2;
return t2;
}