获取之前几个月的js函数
比如我想获取从今天开始往前12个月的数据
4824 热度
1608 浏览
需要传入一个对象,有两个字段
1、num:是往前多少个月 默认是12个月
2、date:需要从哪个日期开始算,比如格式为 2023-09
js
function getPastYearMonths(params = {}) {
let { num = 12, date } = params;
if (typeof num != 'number') {
return console.error('num参数应为数字')
}
// 获取当前日期
var currentDate = date ? new Date(date) : new Date();
// 存储年月的数组
var yearMonths = [];
// 循环获取截止到上个月的前十二个月的年月
for (var i = 0; i < num; i++) {
// 获取年份和月份
var year = currentDate.getFullYear();
var month = currentDate.getMonth() + 1; // 月份从0开始,需要加1
// 将年月格式化为字符串并添加到数组
var yearMonth = year + "-" + (month < 10 ? "0" : "") + month;
yearMonths.push(yearMonth);
// 减少一个月
currentDate.setMonth(currentDate.getMonth() - 1);
}
return yearMonths
}

声明:Web前端小站 - 前端博客 - 王搏的个人博客|版权所有,违者必究|如未注明,均为原创
转载:转载请注明原文链接 - 获取之前几个月的js函数
评论 (0)
0/50
暂无评论,快来抢沙发吧~