快速生成echarts xAxis横坐标年月日、年月份日期序列,输出日期的数组,如[...“2022/07/10“,“2022/07/11“,“2022/07/12“,...]

输出年月日序列数组:[
  "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));

更多日期操作扩展阅读解决全网90%以上的日期格式转换、日期序列等骚操作问题_你挚爱的强哥的博客-CSDN博客function getYearMonthList(startDate, endDate) {//返回月份的数组 如 ['2021/07','2021/08'] var arr = []; var s = new Date(startDate).toLocaleString("zh-Hans-CN", {year: "numeric", month: "2-digit", day: "2-digit"}).split("/"); var e = new Date(endDate)..https://blog.csdn.net/qq_37860634/article/details/118587492

猜你喜欢

转载自blog.csdn.net/qq_37860634/article/details/131877409