import dayjs from 'dayjs' import { formatDate } from './format' /** * 获取时间范围 * @param unit 相差的时间值 * @param unitType 单位 */ export function getDaterange (unit: number, unitType: dayjs.ManipulateType = 'd'): [Date, Date] { const start = dayjs() const end = start.add(unit, unitType) return [start.toDate(), end.toDate()].sort(() => unit) as [Date, Date] } /** * 对时间进行排序 * @param dates 需要排序的时间集合 * @returns 排序后的时间集合 */ export function sortDate (dates: Array) { return dates .sort((prev, next) => dayjs(prev).isBefore(dayjs(next)) ? -1 : 1) } /** * 对时间进行排序 并返回一个dayjs实例集合 * @param dates 需要排序的时间集合 * @returns dayjs实例集合 */ export function sortParserDate (dates: Array) { return dates .map(date => dayjs(date)) .sort((prev, next) => prev.isBefore(next) ? -1 : 1) } /** * 获取两个时间的中间时间段的每月开始时间(包括开始和结束时间) * @param startDate 开始时间 * @param endDate 结束时间 * @returns 时间数组 */ export function getDaterangeMiddleMonthDate (startDate: dayjs.ConfigType, endDate: dayjs.ConfigType) { const [start, end] = sortParserDate([startDate, endDate]) let current = start.set('date', 1) const middleDates: string[] = [] while (!current.isAfter(end)) { if (!start.isAfter(current)) middleDates.push(formatDate(current)) current = current.add(1, 'month') } return middleDates }