Java Unix 时间戳代码片段
Java 示例,涵盖当前纪元秒、毫秒、Instant 转换、时区感知格式化,以及现代的 java.time API。
Current Unix timestamp (seconds)
import java.time.Instant;
Instant.now().getEpochSecond()Current Unix timestamp (milliseconds)
System.currentTimeMillis()
// or
Instant.now().toEpochMilli()Instant from timestamp
import java.time.Instant;
Instant.ofEpochSecond(1700000000)
Instant.ofEpochMilli(1700000000000L)Formatted string (UTC)
import java.time.*;
import java.time.format.DateTimeFormatter;
Instant.ofEpochSecond(1700000000)
.atZone(ZoneOffset.UTC)
.format(DateTimeFormatter.ISO_DATE_TIME)In a specific timezone
import java.time.*;
Instant.ofEpochSecond(1700000000)
.atZone(ZoneId.of("America/New_York"))
.toString()Java 时间戳基础
现代 Java 代码在处理时间戳时应优先使用 java.time.Instant。Instant.now().getEpochSecond() 给出 Unix 秒,Instant.now().toEpochMilli() 给出 Unix 毫秒。
Java 毫秒转 Unix 时间戳
Java 代码常以 System.currentTimeMillis() 开头——一个表示纪元毫秒的 long。要得到以秒为单位的标准 Unix 时间戳,除以 1000。要得到日期,构造一个 Instant。使用下面的显式转换,而不是把这个 long 传给可能期望不同单位的各种 API。
- long millis = System.currentTimeMillis(); // 13 digits, epoch ms
- long secs = System.currentTimeMillis() / 1000L; // millis to Unix timestamp
- Instant inst = Instant.ofEpochMilli(millis); // currentTimeMillis to date (Instant)
- String iso = Instant.ofEpochMilli(millis).toString(); // ISO 8601 UTC
- ZonedDateTime zdt = Instant.ofEpochMilli(millis).atZone(ZoneId.of("UTC"));
- System.nanoTime() 仅用于测量经过的时间——它不是基于纪元的
带时区的 Java 格式化
显示本地时间时,用 ZoneId 把 Instant 转换为 ZonedDateTime。存储和比较保持为 Instant 或 UTC,仅在应用边缘进行格式化。
Java 生产注意事项
java.time API 将时刻、本地日历值和带时区的显示分开。对要存储或比较的时刻使用 Instant。仅在为用户、租户或报表选定 ZoneId 之后才使用 ZonedDateTime。除非旧库需要,否则避免使用旧式的 Date 和 Calendar。
- Unix 秒用 Instant.now().getEpochSecond()
- 毫秒用 Instant.now().toEpochMilli() 或 System.currentTimeMillis()
- 接收标准 Unix 时间戳时用 Instant.ofEpochSecond(seconds)
- 紧凑的 UTC API 输出用 DateTimeFormatter.ISO_INSTANT
FAQ
- 新代码应使用 Date 还是 Instant?
- 用 Instant 来存储和比较时间戳。旧的 Date 可能仍出现在老库中,但 java.time 在秒、毫秒和带时区格式化方面更清晰。
- Instant 与 ZonedDateTime 有什么区别?
- Instant 是 UTC 中的精确时刻。ZonedDateTime 是用 ZoneId 显示的那个时刻,适用于面向用户的日期和报表。
- 如何验证 Java 的纪元值?
- 在保存值之前打印 Instant.ofEpochSecond(seconds) 或 Instant.ofEpochMilli(milliseconds)。ISO 输出应与接收系统期望的 UTC 时刻一致。
- 在 Java 中如何把 millis 转换为 Unix 时间戳?
- 把 System.currentTimeMillis() 除以 1000L 得到 Unix 秒的 long:long secs = System.currentTimeMillis() / 1000L。用 Instant.ofEpochSecond(secs) 可往返回 Instant。
- 在 Java 中如何把 currentTimeMillis 转换为日期?
- 把它包进 Instant:Instant.ofEpochMilli(System.currentTimeMillis())。显示时与 ZoneId 结合:ZonedDateTime.ofInstant(instant, ZoneId.of("UTC")) 或任意其他 IANA 时区。