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 時區。