time.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /**
  2. * 统一时区工具
  3. * 项目时区:Asia/Shanghai (UTC+8)
  4. *
  5. * 前端与服务端通信使用 ISO 8601 格式(UTC),
  6. * 本工具提供本地时区正确的日期边界值。
  7. */
  8. // ⚠️ 与 server/.env 中的 TZ 保持一致,修改时需同步
  9. export const TIMEZONE = 'Asia/Shanghai';
  10. /**
  11. * 获取当前日期字符串(Asia/Shanghai 时区)
  12. * @returns YYYY-MM-DD 格式
  13. */
  14. export function getTodayStr(): string {
  15. const parts = new Intl.DateTimeFormat('zh-CN', {
  16. timeZone: TIMEZONE,
  17. year: 'numeric',
  18. month: '2-digit',
  19. day: '2-digit',
  20. }).formatToParts(new Date());
  21. const year = parts.find(p => p.type === 'year')!.value;
  22. const month = parts.find(p => p.type === 'month')!.value;
  23. const day = parts.find(p => p.type === 'day')!.value;
  24. return `${year}-${month}-${day}`;
  25. }
  26. /**
  27. * 获取某天的起始时间 ISO 字符串(Asia/Shanghai 时区的 00:00:00 → UTC)
  28. * 用于 API 请求的 startDate 参数
  29. * @param daysAgo - 几天前,0=今天,7=7天前,30=30天前
  30. * @returns ISO 8601 格式字符串
  31. */
  32. export function getDayStartISO(daysAgo: number = 0): string {
  33. const now = new Date();
  34. const target = new Date(now.getFullYear(), now.getMonth(), now.getDate() - daysAgo);
  35. return target.toISOString();
  36. }
  37. /**
  38. * 获取今天的起始时间 ISO 字符串
  39. */
  40. export function getTodayStartISO(): string {
  41. return getDayStartISO(0);
  42. }
  43. /**
  44. * 获取 N 天前的 ISO 字符串
  45. */
  46. export function getDaysAgoISO(days: number): string {
  47. const d = new Date();
  48. d.setDate(d.getDate() - days);
  49. return d.toISOString();
  50. }
  51. /**
  52. * 获取 N 月前的 ISO 字符串
  53. */
  54. export function getMonthsAgoISO(months: number): string {
  55. const d = new Date();
  56. d.setMonth(d.getMonth() - months);
  57. return d.toISOString();
  58. }