下面这些 Java 示例以 Unix 秒作为通用基准,只有在运行时天然提供毫秒的地方才展示毫秒。复制之前先回答一个简单的问题:下游那个 API 要的是什么单位?
获取当前 Unix 时间
long seconds = Instant.now().getEpochSecond();
long milliseconds = Instant.now().toEpochMilli();
把时间戳转成 UTC
Instant instant = Instant.ofEpochSecond(1700000000);
String iso = instant.toString();
上生产前留意
存储和传输一律用 Instant。只有在展示或日历逻辑确实需要一个具名区域时,才把它转成 ZonedDateTime。
值跨越系统边界时,把单位写进字段名里:createdAtSeconds 和 createdAtMs 是比 createdAt 长了点,但出事故的时候能省下不少猜测。
Frequent questions:
- Q: 新代码该用 Date 还是 Instant?
- A: 存储和比较时间戳请用 Instant。老库里可能还会见到 Date,但在秒、毫秒和带时区格式化这些事情上,java.time 表达得更清楚。
- Q: Instant 和 ZonedDateTime 有什么区别?
- A: Instant 是 UTC 口径下的确切时刻;ZonedDateTime 是这个时刻配上某个 ZoneId 之后的呈现,适合面向用户的日期和报表。
- Q: 怎么验证 Java 里的 epoch 值?
- A: 保存之前,先打印 Instant.ofEpochSecond(seconds) 或 Instant.ofEpochMilli(milliseconds)。输出的 ISO 字符串应当与接收方期望的 UTC 瞬间一致。
- Q: Java 里怎么把毫秒转成 Unix 时间戳?
- A: 把 System.currentTimeMillis() 除以 1000L 得到 long 型的 Unix 秒:long secs = System.currentTimeMillis() / 1000L。再用 Instant.ofEpochSecond(secs) 可以还原回 Instant。
- Q: Java 里怎么把 currentTimeMillis 转成日期?
- A: 用 Instant 包一层:Instant.ofEpochMilli(System.currentTimeMillis())。要展示的话,再配一个 ZoneId:ZonedDateTime.ofInstant(instant, ZoneId.of("UTC")),换成其他 IANA 时区同理。