输出年月日序列数组:[
"2023/07/01",
"2023/07/02",
"2023/07/03",
"2023/07/04",
"2023/07/05",
"2023/07/06",
"2023/07/07",
"2023/07/08",
"2023/07/09",
"2023/07/10",
"2023/07/11"
]
function getYearMonthDayList(startDate, endDate) {
//startDate、endDate的格式可以为“yyyy/MM/dd”、“yyyy-MM-dd”、“yyyy年MM月dd日”或Date();
//返回年月日的数组,如[..."2022/07/10","2022/07/11","2022/07/12",...]
let st = new Date(startDate), diffDays = parseInt(Math.abs(new Date(endDate) - st) / (1000 * 60 * 60 * 24));
return [...Array(diffDays + 1)].map((v, i) => new Date(new Date(startDate).setDate(st.getDate() + i)).toLocaleString("zh-Hans-CN", { year: "numeric", month: "2-digit", day: "2-digit" }))
}
console.log(JSON.stringify(getYearMonthDayList('2022/7/1', '2022/7/11'), null, 2));
输出年月序列数组:[
"2021/7",
"2021/8",
"2021/9",
"2021/10",
"2021/11",
"2021/12",
"2022/1",
"2022/2",
"2022/3",
"2022/4",
"2022/5",
"2022/6",
"2022/7"
]
function getYearMonthList(startDate, endDate) {
//startDate、endDate的格式可以为“yyyy/MM”、“yyyy-MM”、“yyyy年MM月”或Date();
//返回月份的数组,如 [..."2022/1","2022/2","2022/3",...]
let st = new Date(startDate), sd = st, sy = sd.getFullYear(), sm = sd.getMonth() + 1, sms = sy * 12 + sm, ed = new Date(endDate), ey = ed.getFullYear(), em = ed.getMonth() + 1, ems = ey * 12 + em;
let diffMonths = Math.abs(ems - sms);
return [...Array(diffMonths + 1)].map((v, i) => new Date(new Date(startDate).setMonth(st.getMonth() + i)).toLocaleString("zh-Hans-CN", { year: "numeric", month: "short" }).replace("年", "/").replace("月", ""))
}
console.log(JSON.stringify(getYearMonthList('2021/7', '2022/7'), null, 2));