获取最近 30 天的日期(不包括今天)格式只有天
想要格式为年月日的参考
原文链接:http://www.childsay.com/js-last-30-dates.html
其实也就在在push的时候把年月加上 比如
dates.push(`${endYear}-${endMonthString}-${item}`);
const _ = require('lodash');
const dayjs = require('dayjs');
const last30dates= ()=> {
const endDayjs = dayjs();
const endYear = endDayjs.year();
const endMonth = endDayjs.month() + 1;
const endMonthString = endMonth < 10 ? '0' + endMonth.toString() : endMonth.toString();
const endDate = endDayjs.date();
const startDayjs = dayjs().subtract(30, 'days');//想包括今天的话30改成29
const startYear = startDayjs.year();
const startMonth = startDayjs.month() + 1;
const startMonthString = startMonth < 10 ? '0' + startMonth.toString() : startMonth.toString();
const startDate = startDayjs.date();
const dates = [];
if (endMonth === startMonth) {
// 同一个月,直接改变天数
_.each(_.range(startDate, endDate + 1), (item) => {
if (item < 10) {
item = '0' + item.toString();
}
dates.push(`${item}`);
});
} else if (endMonth === startMonth + 1 || startMonth - endMonth === 11) {
// 上一个月和当前月
// 上个月
_.each(_.range(startDate, startDayjs.daysInMonth() + 1), (item) => {
if (item < 10) {
item = '0' + item.toString();
}
dates.push(`${item}`);
});
// 当前月
_.each(_.range(1, endDate), (item) => { //想包括今天的话endDate+1
if (item < 10) {
item = '0' + item.toString();
}
dates.push(`${item}`);
});
} else if (endMonth === startMonth + 2) {
// 上上个月、上个月和当前月,遇到 2 月时
// 上上个月
_.each(_.range(startDate, startDayjs.daysInMonth() + 1), (item) => {
if (item < 10) {
item = '0' + item.toString();
}
dates.push(`${item}`);
});
// 2 月
_.each(_.range(1, startDayjs.add(1, 'months').daysInMonth() + 1), (item) => {
if (item < 10) {
item = '0' + item.toString();
}
dates.push(`${item}`);
});
// 当前月
_.each(_.range(1, endDate + 1), (item) => {
if (item < 10) {
item = '0' + item.toString();
}
dates.push(`${item}`);
});
}
console.log(dates)
return dates;
}
输出