0
0

More than 1 year has passed since last update.

OffsetDateTimeからTimestampに変換

Posted at

Javaのjava.timeパッケージを使ってOffsetDateTimeからTimestampに変換するためのコード

import java.sql.Timestamp;
import java.time.OffsetDateTime;

public class Main {
    public static void main(String[] args) {
        // 現在のOffsetDateTimeを取得
        OffsetDateTime offsetDateTime = OffsetDateTime.now();

        // OffsetDateTimeからTimestampに変換
        Timestamp timestamp = Timestamp.from(offsetDateTime.toInstant());

        System.out.println("OffsetDateTime: " + offsetDateTime);
        System.out.println("Timestamp: " + timestamp);
    }
}

このコードは、現在の日時をOffsetDateTimeとして取得し、それをTimestampに変換します。そして、両方の日時を出力します。

ただし、Timestampは古い日付・時刻APIであり、Java 8以降ではjava.timeパッケージのクラス(LocalDateTime, ZonedDateTime, OffsetDateTimeなど)を使うことが推奨されています。これらのクラスは、日付と時刻をより直感的かつ安全に扱うことができます。なので、あなたが古いライブラリやフレームワークとの互換性など特別な理由がない限り、新しいAPIを使うことを検討してみてください。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0