Java Convert Timestamp to OffsetDateTime

Tags: Java Timestamp Java OffsetDateTime Java 8

In this Java core tutorial we learn how to convert a java.sql.Timestamp object to a java.time.OffsetDateTime object in Java programming language.

How to convert Timestamp to OffsetDateTime in Java

In Java, with a given Timestamp object we can follow these step to convert it to a OffsetDateTime object.

  • Step 1: use the Timestamp.toLocalDateTime() method to convert the Timestamp object to a LocalDateTime object.
  • Step 1: use the LocalDateTime.atOffset(ZoneOffset offset) method to convert the LocalDateTime object of step 1 to a OffsetDateTime object.

ConvertTimestampToOffsetDateTimeExample1.java

import java.sql.Timestamp;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;

public class ConvertTimestampToOffsetDateTimeExample1 {
    public static void main(String... args) {
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());

        // Convert Timestamp object to OffsetDateTime object
        LocalDateTime localDateTime = timestamp.toLocalDateTime();
        ZoneOffset systemZoneOffset = ZoneId.systemDefault().getRules().getOffset(Instant.now());
        OffsetDateTime offsetDateTime = localDateTime.atOffset(systemZoneOffset);

        System.out.println("Timestamp: " + timestamp);
        System.out.println("OffsetDateTime: " + offsetDateTime);
    }
}
The output as below.
Timestamp: 2022-05-24 18:43:44.902
OffsetDateTime: 2022-05-24T18:43:44.902+07:00

Happy Coding 😊

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

Java Convert Timestamp to Instant

Java Convert OffsetDateTime to Timestamp