Files
lislgosms/api/src/common/shanghai-date-range.ts
T

25 lines
1.2 KiB
TypeScript

import { BadRequestException } from '@nestjs/common';
const DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
function parseBoundary(value: string | undefined, endOfDay: boolean) {
if (!value) return undefined;
if (!DATE_PATTERN.test(value)) throw new BadRequestException('日期格式必须为 YYYY-MM-DD');
const [year, month, day] = value.split('-').map(Number);
const calendarDate = new Date(Date.UTC(year, month - 1, day));
if (calendarDate.getUTCFullYear() !== year || calendarDate.getUTCMonth() !== month - 1 || calendarDate.getUTCDate() !== day) {
throw new BadRequestException('日期无效');
}
const parsed = new Date(`${value}T${endOfDay ? '23:59:59.999' : '00:00:00'}+08:00`);
if (Number.isNaN(parsed.getTime())) throw new BadRequestException('日期无效');
return parsed;
}
/** Converts UI calendar dates to an inclusive Asia/Shanghai database range. */
export function shanghaiDateRange(from?: string, to?: string) {
const gte = parseBoundary(from, false);
const lte = parseBoundary(to, true);
if (gte && lte && gte > lte) throw new BadRequestException('开始日期不能晚于结束日期');
return gte || lte ? { gte, lte } : undefined;
}