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を使うことを検討してみてください。