本文最后更新于 397 天前,其中的信息可能已经有所发展或是发生改变。
// 修改后的getYearMonthStr函数,返回"YYYY/MM"格式的字符串
const getYearMonthStr = (preDate, addMonths) => {
let d = preDate ? new Date(preDate) : new Date();
d.setMonth(d.getMonth() + addMonths); // 使用加法来往后推月份
let year = d.getFullYear();
let month = d.getMonth() + 1; // getMonth()返回的月份是从0开始的
return `${year}/${String(month).padStart(2, '0')}`; // 使用padStart确保月份是两位数
};
// 示例使用
let array = [];
for (let i = 1; i <= 12; i++) { // 从1开始循环,直到12,不包括"2024/01"本身
let preMonth = getYearMonthStr("2024/01", i);
// 根据年月字符串获取月份,并转换为中文月份
let monthStr = preMonth.split('/')[1] + '月'; // 获取月份部分并添加"月"
array.push(monthStr); // 直接添加到数组中
}
console.log(array);
往前推12月
// 修改后的getYearMonthStr函数,返回"YYYY/MM"格式的字符串
const getYearMonthStr = (preDate, minusMonths) => {
let d = preDate ? new Date(preDate) : new Date();
d.setMonth(d.getMonth() - minusMonths); // 使用减法来往前推月份
let year = d.getFullYear();
let month = d.getMonth() + 1; // getMonth()返回的月份是从0开始的
return `${year}/${String(month).padStart(2, '0')}`; // 使用padStart确保月份是两位数
};
// 示例使用
let array = [];
for (let i = 1; i <= 12; i++) { // 从1开始循环,直到12,不包括"2024/01"本身
let preMonth = getYearMonthStr("2024/01", i);
// 根据年月字符串获取月份,并转换为中文月份
let monthStr = preMonth.split('/')[1] + '月'; // 获取月份部分并添加"月"
array.unshift(monthStr); // 使用unshift来保持逆序添加到数组中
}
console.log(array);
日期对象兼容问题
```js
let d = netsales[0].ac_ym ? new Date(netsales[0].ac_ym + "/01") : new Date();
d.setMonth(d.getMonth() - i);
let month = d.getMonth() + 1;
```
yy/dd/ss这样格式