Java中时间戳与Instant互相转换直接:时间戳→Instant用Instant.ofEpochMilli(long),Instant→时间戳用toEpochMilli()(毫秒)或getEpochSecond()(秒),全程基于UTC纪元,无时区干扰,无需Date等中间转换。

Java 中时间戳(毫秒值)与 Instant 的互相转换非常直接,核心在于理解两者本质:时间戳是自 1970-01-01T00:00:00Z(UTC)起经过的毫秒数;Instant 是 Java 8 引入的不可变时间点,也基于同一纪元,单位为纳秒。
时间戳 → Instant
使用 Instant.ofEpochMilli(long) 方法即可。该方法接受毫秒级时间戳,自动转为对应的 Instant 对象。
- 若时间戳为
long timestamp = 1717023600000L(对应 2024-05-30 15:00:00 UTC),调用Instant instant = Instant.ofEpochMilli(timestamp)即可得到精确到毫秒的 Instant - 注意:该方法不接受负数以外的非法值(如
Long.MIN_VALUE可能触发异常),但常规业务时间戳基本无风险 - 如果只有秒级时间戳(如 Unix 秒),可用
Instant.ofEpochSecond(long),避免手动乘 1000
Instant → 时间戳
Instant 提供两个常用方法获取时间戳:
-
instant.toEpochMilli():返回毫秒级时间戳(long),最常用,兼容大多数数据库、前端和旧系统 -
instant.getEpochSecond():返回秒级时间戳(long),适合日志归档、缓存过期等对精度要求不高的场景 - 如需纳秒部分(例如做高精度计时),可用
instant.getNano(),但注意它只返回 0–999,999,999 范围内的纳秒偏移,不是总纳秒数
注意事项与常见误区
转换本身无时区参与,Instant 始终代表 UTC 时间点,因此转换是纯数值映射,安全可靠。
- 不要用
new Date(timestamp).toInstant()做中间转换——冗余且无必要 - 避免误用
LocalDateTime或ZonedDateTime参与转换,它们含时区或本地语义,会引入歧义 - 数据库中存储为
BIGINT的时间戳,读取后可直接传给ofEpochMilli;写回时调用toEpochMilli()即可
简单示例代码
// 毫秒时间戳转 InstantInstant instant = Instant.ofEpochMilli(1717023600000L);
// Instant 转毫秒时间戳long ts = instant.toEpochMilli(); // 结果仍是 1717023600000L
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











