dayjs 获取过去六个月每个月的开始日期和结束日期

js yekong

vue 数据大屏项目 开发中,展示echarts柱状图,最近半年的数据,因为接口需要传开始和结束日期来查询数据,所以我们需要把先获取过去6个月的日期,并且还需要获取这个6个月的开始日期和结束如期。

引入dayjs

import dayjs from "dayjs";

代码

for (var i = 0; i < 6; i++) {
  this.list.push({
    title: dayjs().subtract((6 - i) - 1, 'month').format("MM"),
    value: 0,
    value2: 0,
    id: dayjs().subtract((6 - i)  - 1, 'month').format("MM"),
    start: dayjs(dayjs().subtract((6 - i)  - 1, 'month').format("YYYY-MM-DD")).startOf('month').format("YYYY-MM-DD"),
    end: dayjs(dayjs().subtract((6 - i)  - 1, 'month').format("YYYY-MM-DD")).endOf('month').format("YYYY-MM-DD"),
  })
  this.xData.push(dayjs().subtract((6 - i)  - 1, 'month').format("MM"))
}

这样就得到了这6个月的开始日期和结束日期了。

[{"title":"12","value":0,"value2":0,"id":"12","start":"2022-12-01","end":"2022-12-31"},{"title":"01","value":0,"value2":0,"id":"01","start":"2023-01-01","end":"2023-01-31"},{"title":"02","value":0,"value2":0,"id":"02","start":"2023-02-01","end":"2023-02-28"},{"title":"03","value":0,"value2":0,"id":"03","start":"2023-03-01","end":"2023-03-31"},{"title":"04","value":0,"value2":0,"id":"04","start":"2023-04-01","end":"2023-04-30"},{"title":"05","value":0,"value2":0,"id":"05","start":"2023-05-01","end":"2023-05-31"}]
喜欢