import dayjs from 'dayjs'; import type { Dayjs } from 'dayjs'; export interface RangePreset { label: string; value: [Dayjs, Dayjs]; } export const defaultShortcuts: RangePreset[] = [ { label: '今天', value: [dayjs().startOf('d'), dayjs().endOf('d')] }, { label: '昨天', value: [dayjs().subtract(1, 'd').startOf('d'), dayjs().subtract(1, 'd').endOf('d')] }, { label: '最近七天', value: [dayjs().subtract(7, 'd').startOf('d'), dayjs().endOf('d')] }, { label: '最近 30 天', value: [dayjs().subtract(30, 'd').startOf('d'), dayjs().endOf('d')] }, { label: '本月', value: [dayjs().startOf('month'), dayjs().endOf('d')] }, { label: '今年', value: [dayjs().startOf('year'), dayjs().endOf('d')] }, ]; export function formatDate( date: Date | string | number | Dayjs | null | undefined, format = 'YYYY-MM-DD HH:mm:ss', ): string { if (!date) return ''; return dayjs(date).format(format); } export function formatPast(param: string | Date | number, format = 'YYYY-MM-DD HH:mm:ss'): string { const t = new Date(param).getTime(); const time = Date.now() - t; if (time < 10000) return '刚刚'; if (time < 60000) return `${Math.floor(time / 1000)}秒前`; if (time < 3600000) return `${Math.floor(time / 60000)}分钟前`; if (time < 86400000) return `${Math.floor(time / 3600000)}小时前`; if (time < 259200000) return `${Math.floor(time / 86400000)}天前`; return formatDate(new Date(param), format); } export function formatAxis(param: Date | string | number = new Date()): string { const hour = new Date(param).getHours(); if (hour < 6) return '凌晨好'; if (hour < 9) return '早上好'; if (hour < 12) return '上午好'; if (hour < 14) return '中午好'; if (hour < 17) return '下午好'; if (hour < 19) return '傍晚好'; if (hour < 22) return '晚上好'; return '夜里好'; } export function dateFormatter(cellValue: Date | string | number | null | undefined): string { return cellValue ? formatDate(cellValue) : ''; } export function dateFormatter2(cellValue: Date | string | number | null | undefined): string { return cellValue ? formatDate(cellValue, 'YYYY-MM-DD') : ''; } export function beginOfDay(param: Date): Date { return new Date(param.getFullYear(), param.getMonth(), param.getDate(), 0, 0, 0); } export function endOfDay(param: Date): Date { return new Date(param.getFullYear(), param.getMonth(), param.getDate(), 23, 59, 59); } export function convertDate(param: Date | string): Date { if (typeof param === 'string') return new Date(param); return param; }