java.time.Instantとjava.sql.Timestampの間の変換

java.time.Instantとjava.sql.Timestamp間の変換

1. 概要

java.time.Instantクラスとjava.sql.Timestampクラスはどちらも、UTCのタイムライン上のポイントを表します。 つまり、the Java epoch以降のナノ秒数を表します。

このクイックチュートリアルでは、組み込みのJavaメソッドを使用して一方を他方に変換します。

2. InstantTimestampに変換して元に戻す

Timestamp.from()を使用して、Instantsをタイムスタンプに変換できます。

Instant instant = Instant.now();
Timestamp timestamp = Timestamp.from(instant);
assertEquals(instant.toEpochMilli(), timestamp.getTime());

逆に、Timestamp.toInstant()を使用してTimestampsをInstantsに変換できます。__

instant = timestamp.toInstant();
assertEquals(instant.toEpochMilli(), timestamp.getTime());

いずれにせよ、InstantTimestampの両方が、タイムライン上の同じポイントを表します。

次に、2つのクラスとタイムゾーンの間の相互作用を見てみましょう。

3. toString()メソッドの違い

Invoking toString() on Instant and Timestamp behaves differently with respect to timezone.Instant.toString()は、UTCタイムゾーンで時刻を返します。 一方、Timezone.toString()は、ローカルマシンのタイムゾーンの時間を返します。

instanttimezoneでそれぞれtoString()を呼び出すと、何が得られるかを見てみましょう。

Instant (in UTC): 2018-10-18T00:00:57.907Z
Timestamp (in GMT +05:30): 2018-10-18 05:30:57.907

Here, timestamp.toString()の結果、instant.toString().によって返された時刻から5時間30分後の時刻になりました。これは、ローカルマシンのタイムゾーンがGMT + 5:30タイムゾーンであるためです。

The output of the toString() method is different, but both the timestamp and instant represent the same point on the timeline

TimestampをUTCタイムゾーンに変換することでこれを確認することもできます。

DateFormat df = DateFormat.getDateTimeInstance();
df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss:SS'Z'");
df.setTimeZone(TimeZone.getTimeZone("UTC"));

assertEquals(instant.toString(), df.format(timestamp).toString());

4. 結論

このクイックチュートリアルでは、組み込みメソッドを使用してJavaでjava.time.Instantクラスとjava.sql.Timestampクラスを変換する方法を説明しました。

また、タイムゾーンが出力の変化にどのように影響するかを確認しました。

そして、いつものように、完全なコード例はover on GitHubで利用できます。