import dayjs from 'dayjs'
//获取近几年的年份
export function handleLastYearList(num = 5, year?: string | number) {
if (year) year = year.toString()
const currentYear = year ? new Date(year).getFullYear() : new Date().getFullYear()
const originYearList = []
for (let i = 0; i < num; i++) {
originYearList.push(`${currentYear - i}`)
}
return originYearList.reverse()
}
//获取近几月的月份
export function handleLastMonthList(num = 12, separator = '-', month?: string) {
let data = new Date()
const result = []
if (month) {
data = new Date(month)
}
data.setMonth(data.getMonth() + 1, 1)
for (let i = 0; i < num; i++) {
data.setMonth(data.getMonth() - 1)
let m: string | number = data.getMonth() + 1
m = m < 10 ? '0' + m : m
result.push(`${data.getFullYear()}${separator}${m}`)
}
return result.reverse()
}
//获取近几天的日期
export function handleLastDayList(num = 10, format = 'YYYY-MM-DD') {
const result = []
const time = +new Date()
const oneDayTime = 24 * 60 * 60 * 1000
for (let i = 0; i < num; i++) {
const daytime = time - i * oneDayTime
const formatTime = dayjs(daytime).format(format)
result.push(formatTime)
}
return result.reverse()
}
// 获取前几个季度
function getLast4Quarters(count = 5, date?: string) {
const quarters = [] // 季度的结果
const result: string[] = []
let currentDate = new Date() // 获取当前日期
if (date) {
currentDate = new Date(date)
}
const currentYear = currentDate.getFullYear() // 获取当前年
let currentMonth = currentDate.getMonth() // 获取当前月份
for (let i = 0; i < count; i++) {
const currentQuarter = Math.floor(currentMonth / 3) + 1 // 计算当前季度
quarters.push(currentQuarter) // 将当前季度存入数组中
currentMonth -= 3 // 计算上一个季度的月份
}
quarters.forEach((ele) => {
if (ele > 0) {
result.push(currentYear + '年第' + ele + '季度')
} else {
const year = currentYear - 1 - Math.abs(Math.ceil(ele / 4))
const num = 4 + (ele % 4)
result.push(year + '年第' + num + '季度')
}
})
return result.reverse()
}