Java Convert OffsetDateTime to Timestamp
Tags: Java OffsetDateTime Java Timestamp Java 8
In this Java core tutorial we learn how to convert a java.time.OffsetDateTime object to a java.sql.Timestamp object in Java programming language.
How to convert OffsetDateTime to Timestamp in Java
In the first solution below we can follow these steps to convert OffsetDateTime object to Timestamp object.
- Step 1: convert OffsetDateTime object to Instant object using the OffsetDateTime.toInstant() method.
- Step 2: convert the the Instant object of step 1 to Timestamp object using Timestamp.from(Instant instant) method.
ConvertOffsetDateTimeToTimestampExample1.java
import java.sql.Timestamp;
import java.time.Instant;
import java.time.OffsetDateTime;
public class ConvertOffsetDateTimeToTimestampExample1 {
public static void main(String... args) {
OffsetDateTime offsetDateTime = OffsetDateTime.now();
// Convert OffsetDateTime object to Timestamp object
Instant instant = offsetDateTime.toInstant();
Timestamp timestamp = Timestamp.from(instant);
System.out.println("OffsetDateTime: " + offsetDateTime);
System.out.println("Timestamp: " + timestamp);
}
}
OffsetDateTime: 2022-05-24T18:48:55.529481300+07:00
Timestamp: 2022-05-24 18:48:55.5294813
The second solution below we can follow these steps to convert OffsetDateTime object to Timestamp object.
- Step 1: convert OffsetDateTime object to LocalDateTime object using the OffsetDateTime.toLocalDateTime() method.
- Step 2: convert the the LocalDateTime object of step 1 to Timestamp object using Timestamp.valueOf(LocalDateTime dateTime) method.
ConvertOffsetDateTimeToTimestampExample2.java
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
public class ConvertOffsetDateTimeToTimestampExample2 {
public static void main(String... args) {
OffsetDateTime offsetDateTime = OffsetDateTime.now();
// Convert OffsetDateTime object to Timestamp object
LocalDateTime localDateTime = offsetDateTime.toLocalDateTime();
Timestamp timestamp = Timestamp.valueOf(localDateTime);
System.out.println("OffsetDateTime: " + offsetDateTime);
System.out.println("Timestamp: " + timestamp);
}
}
OffsetDateTime: 2022-05-24T18:49:20.817835900+07:00
Timestamp: 2022-05-24 18:49:20.8178359
Happy Coding 😊
Related Articles
Java Convert ZonedDateTime to Timestamp
Java Convert LocalDate to Timestamp
Java Convert Instant to Timestamp
Java Convert LocalDateTime to Timestamp
Java Convert Timestamp to LocalDateTime
Java Convert Timestamp to ZonedDateTime
Java Convert Timestamp to LocalDate