获取当年/当季/当月时间段、获取时间段内所有天/月
安装依赖
npm install moment --save
import moment from 'moment'
Vue.prototype.$moment = moment
获取时间段 当年/当季/当月
getTimeRange(type) {
let range = []
if (type == 1) {
// 当日
range = [
this.$moment().format('YYYY-MM-DD'),
this.$moment().format('YYYY-MM-DD')
]
} else if (type == 2) {
// 当月
range = [
this.$moment().startOf('month').format('YYYY-MM-DD'),
this.$moment().endOf('month').format('YYYY-MM-DD')
]
} else if (type == 3) {
// 当季度
range = [
this.$moment().startOf('quarter').format('YYYY-MM-DD'),
this.$moment().endOf('quarter').format('YYYY-MM-DD')
]
} else if (type == 4) {
// 当年
range = [
this.$moment().startOf('year').format('YYYY-MM-DD'),
this.$moment().endOf('year').format('YYYY-MM-DD')
]
} else if (type == 5) {
// 上月
range = [
this.$moment().add(-1, 'M').startOf('month').format('YYYY-MM-DD'),
this.$moment().add(-1, 'M').endOf('month').format('YYYY-MM-DD')
]
} else if (type == 6) {
// 上季度
range = [
this.$moment().add(-1, 'Q').startOf('quarter').format('YYYY-MM-DD'),
this.$moment().add(-1, 'Q').endOf('quarter').format('YYYY-MM-DD')
]
} else {}
return range
}
用法:
this.getTimeRange(4) // 当年 ['2021-01-01', '2021-12-31']
获取时间段内每 月/天
fullDate({ startTime, endTime, type = 'day' }) { // ({ 开始时间, 结束时间, 类型-天/月 })
const addType = type == 'month' ? 'months' : 'days' // +1 月/日
const format = type == 'month' ? 'YYYY-MM' : 'YYYY-MM-DD' // 日期格式
const endTimeStemp = type == 'month' ? new Date(this.$moment(endTime).format('YYYY-MM-01')).getTime() : new Date(endTime).getTime() // 结束时间时间戳
const list = [this.$moment(startTime).format(format)]
let i = 1
while (new Date(list[list.length - 1]).getTime() < endTimeStemp) {
list.push(this.$moment(startTime).add(i, addType).format(format))
i++
}
return list
},
用法:
this.fullDate({ startTime: '2021-10-01', endTime: '2021-12-31', type: 'month' }) // 所有月 ['2021-10', '2021-11', '2021-12']
this.fullDate({ startTime: '2021-10-01', endTime: '2021-12-31', type: 'day' }) // 所有天 ['2021-10-01', '2021-10-02', ... , '2021-12-31']