Java Convert ZonedDateTime to Timestamp
Tags: Java ZonedDateTime Java Timestamp Java 8
In this Java core tutorial we learn how to convert a java.time.ZonedDateTime object to a java.sql.Timestamp object in Java programming language.
How to convert ZonedDateTime to Timestamp in Java
In the first solution below we can follow these steps to convert ZonedDateTime object to Timestamp object.
- Step 1: convert ZonedDateTime object to Instant object using the ZonedDateTime.toInstant() method.
- Step 2: convert the above Instant object to Timestamp object using Timestamp.from(Instant instant) method.
ConvertZonedDateTimeToTimestampExample1.java
import java.sql.Timestamp;
import java.time.Instant;
import java.time.ZonedDateTime;
public class ConvertZonedDateTimeToTimestampExample1 {
public static void main(String... args) {
ZonedDateTime zonedDateTime = ZonedDateTime.now();
// Convert ZonedDateTime object to Timestamp object
Instant instant = zonedDateTime.toInstant();
Timestamp timestamp = Timestamp.from(instant);
System.out.println("ZonedDateTime: " + zonedDateTime);
System.out.println("Timestamp: " + timestamp);
}
}
ZonedDateTime: 2022-05-22T19:30:38.418073400+07:00[Asia/Bangkok]
Timestamp: 2022-05-22 19:30:38.4180734
The second solution below we can follow these steps to convert ZonedDateTime object to Timestamp object.
- Step 1: convert ZonedDateTime object to LocalDateTime object using the ZonedDateTime.toLocalDateTime() method.
- Step 2: convert the above LocalDateTime object to Timestamp object using Timestamp.valueOf(LocalDateTime dateTime) method.
ConvertZonedDateTimeToTimestampExample2.java
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
public class ConvertZonedDateTimeToTimestampExample2 {
public static void main(String... args) {
ZonedDateTime zonedDateTime = ZonedDateTime.now();
// Convert ZonedDateTime object to Timestamp object
LocalDateTime localDateTime = zonedDateTime.toLocalDateTime();
Timestamp timestamp = Timestamp.valueOf(localDateTime);
System.out.println("ZonedDateTime: " + zonedDateTime);
System.out.println("Timestamp: " + timestamp);
}
}
ZonedDateTime: 2022-05-22T19:30:58.243393600+07:00[Asia/Bangkok]
Timestamp: 2022-05-22 19:30:58.2433936
Happy Coding 😊
Related Articles
Java Convert LocalDate to Timestamp
Java Convert LocalDateTime to Timestamp