前后端传递 Date 用什么类型好?

By | 7月 6, 2026

不推荐:数字类型(Unix timestamp)

缺点

  • 不可读
  • 歧义:不知道是秒,毫秒,微秒?
  • 跨语言易踩坑
    • Java:Instant.now().toEpochMilli() – 毫秒
    • Python:time.time() – 秒
    • Javascript:Date.now() – 毫秒

如果非要用 number,field 名字加上后缀,例如:

  • createdTimeEpochMs: number

推荐:ISO8601 格式的 UTC 字符串

ISO8601: 日期 format 的国际标准

  • Date in UTC: 2026-07-06
  • Time in UTC: 02:19:52Z, T021952Z
  • Date and Time in UTC: 2026-07-06T02:19:52Z, 20260706T021952Z
  • Week: 2026-W28
  • Week with weekday: 2026-W28-1

UTC (Coordinated Universal Time): 全球统一的标准时间基准。

Javascript

const date: Date = new Date("2026-07-06T10:30:00Z");
const isoStr: string = new Date().toISOString();  // 2026-07-06T03:44:23.012Z

Java

Instant instant = Instant.parse("2026-07-06T10:30:00Z");
String isoStr = Instant.now().toString();  // 2026-07-06T10:30:00.123Z

Python

dt = datetime.fromisoformat("2026-07-06T10:30:00+00:00")
iso_str = datetime.now(timezone.utc).isoformat()  # 2026-07-06T10:30:00.123456+00:00