| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- /**
- * 统一时区工具
- * 项目时区:Asia/Shanghai (UTC+8)
- *
- * 前端与服务端通信使用 ISO 8601 格式(UTC),
- * 本工具提供本地时区正确的日期边界值。
- */
- // ⚠️ 与 server/.env 中的 TZ 保持一致,修改时需同步
- export const TIMEZONE = 'Asia/Shanghai';
- /**
- * 获取当前日期字符串(Asia/Shanghai 时区)
- * @returns YYYY-MM-DD 格式
- */
- export function getTodayStr(): string {
- const parts = new Intl.DateTimeFormat('zh-CN', {
- timeZone: TIMEZONE,
- year: 'numeric',
- month: '2-digit',
- day: '2-digit',
- }).formatToParts(new Date());
- const year = parts.find(p => p.type === 'year')!.value;
- const month = parts.find(p => p.type === 'month')!.value;
- const day = parts.find(p => p.type === 'day')!.value;
- return `${year}-${month}-${day}`;
- }
- /**
- * 获取某天的起始时间 ISO 字符串(Asia/Shanghai 时区的 00:00:00 → UTC)
- * 用于 API 请求的 startDate 参数
- * @param daysAgo - 几天前,0=今天,7=7天前,30=30天前
- * @returns ISO 8601 格式字符串
- */
- export function getDayStartISO(daysAgo: number = 0): string {
- const now = new Date();
- const target = new Date(now.getFullYear(), now.getMonth(), now.getDate() - daysAgo);
- return target.toISOString();
- }
- /**
- * 获取今天的起始时间 ISO 字符串
- */
- export function getTodayStartISO(): string {
- return getDayStartISO(0);
- }
- /**
- * 获取 N 天前的 ISO 字符串
- */
- export function getDaysAgoISO(days: number): string {
- const d = new Date();
- d.setDate(d.getDate() - days);
- return d.toISOString();
- }
- /**
- * 获取 N 月前的 ISO 字符串
- */
- export function getMonthsAgoISO(months: number): string {
- const d = new Date();
- d.setMonth(d.getMonth() - months);
- return d.toISOString();
- }
|