Java Snippets

Java の Unix タイムスタンプ スニペット

現在のエポック秒、ミリ秒、Instant による変換、タイムゾーン対応の整形、最新の java.time API を扱う Java の例。

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 の millis を 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 でミリ秒を 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 ゾーン。