60 lines
1.8 KiB
TypeScript
60 lines
1.8 KiB
TypeScript
import type { DateQuickPick } from './types';
|
|
|
|
export type DateRangeMode = DateQuickPick | 'custom';
|
|
|
|
export interface DateRangeValue {
|
|
start: string;
|
|
end: string;
|
|
}
|
|
|
|
const LABELS: Record<DateQuickPick, string> = {
|
|
thisWeek: '本周',
|
|
thisMonth: '本月',
|
|
last15: '近 15 天',
|
|
};
|
|
|
|
function fmtYmd(date: Date): string {
|
|
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
|
|
}
|
|
|
|
function addDays(date: Date, days: number): Date {
|
|
const next = new Date(date);
|
|
next.setDate(next.getDate() + days);
|
|
return next;
|
|
}
|
|
|
|
export function getQuickDateRange(pick: DateQuickPick, now = new Date()): DateRangeValue {
|
|
const today = new Date(now);
|
|
today.setHours(0, 0, 0, 0);
|
|
if (pick === 'thisWeek') {
|
|
const day = today.getDay() || 7;
|
|
return { start: fmtYmd(addDays(today, -(day - 1))), end: fmtYmd(today) };
|
|
}
|
|
if (pick === 'thisMonth') {
|
|
return { start: fmtYmd(new Date(today.getFullYear(), today.getMonth(), 1)), end: fmtYmd(today) };
|
|
}
|
|
return { start: fmtYmd(addDays(today, -14)), end: fmtYmd(today) };
|
|
}
|
|
|
|
export function normalizeDateRange(start: string, end: string): DateRangeValue {
|
|
return start <= end ? { start, end } : { start: end, end: start };
|
|
}
|
|
|
|
export function inferDateRangeMode(start: string, end: string, now = new Date()): DateRangeMode {
|
|
const range = normalizeDateRange(start, end);
|
|
const match = QUICK_DATE_OPTIONS.find(({ id }) => {
|
|
const quickRange = getQuickDateRange(id, now);
|
|
return quickRange.start === range.start && quickRange.end === range.end;
|
|
});
|
|
return match?.id ?? 'custom';
|
|
}
|
|
|
|
export function dateRangeModeLabel(mode: DateRangeMode): string {
|
|
return mode === 'custom' ? '自定义区间' : LABELS[mode];
|
|
}
|
|
|
|
export const QUICK_DATE_OPTIONS = (Object.keys(LABELS) as DateQuickPick[]).map(id => ({
|
|
id,
|
|
label: LABELS[id],
|
|
}));
|