- 两个月之间年月
(`// 两个月之间年月
例子(2024,1,2024,3)
yearsMonthsDiff(year1: number, month1: number, year2: any, month2: any) {
let yearsDiff = year2 - year1;
let monthsDiff = month2 - month1;
let oldy = year1;
let oldM = month1;
// 如果实际月数差小于0,则年数需减1
if (monthsDiff < 0) {
yearsDiff--;
monthsDiff += 12;
}
let pushFor = [];
let day = yearsDiff * 12 + monthsDiff;//得到两个日期之间的天数
// let yearMore=0
if (day > 0) {
for (let i = 0; i < day; i++) {
// 如果实际月数差小于0,则年数需减1
let pushM: number = oldM + i;
console.log(pushM, "月");
if (pushM > 12) {
year1 = oldy + 1; //只支持跨一年
pushM = pushM - 12;
//if(pushM==13){//记录一次跨年 (多年)
// yearMore++
// year1+=yearMore
// }
const yearMonth = year1 + "-" + (pushM < 10 ? "0" + pushM : pushM); // 转换为字符串格式
pushFor.push(yearMonth); // 添加到数组前面
}
return pushFor;//2023-01,2023-02
}
}`
2.获取前三个月日期
getLastThreeMonths() {
const now = new Date();
let months = [];
for (let i = -1; i < 2; i++) {
let year: any = now.getFullYear();
let month = now.getMonth() - i;//获取月份是now.getMonth() + 1所以初始值为-1
if (month <= 0) {
// 如果超过了当前年份的月份,则加-1+12=11,0+12=12
month += 12;
year--;
}
const yearMonth = year + "-" + (month < 10 ? "0" + month : month);
months.unshift(yearMonth); // 添加到数组前面
}
return months;
}