Java Convert SQL Date to OffsetDateTime

Tags: Java SQL Date Java OffsetDateTime Java 8

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

How to convert SQL Date to OffsetDateTime in Java

In Java, with a given SQL Date object we can follow these steps to convert it to a OffsetDateTime object.

  • Step 1: use Date.toLocalDate() method to convert the SQL Date object to a LocalDate object.
  • Step 2: use LocalDate.atTime(OffsetTime time) method to convert the LocalDate object from step 1 to a OffsetDateTime object.

ConvertSQLDateToOffsetDateTimeExample1.java

import java.sql.Date;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.time.OffsetTime;

public class ConvertSQLDateToOffsetDateTimeExample1 {
    public static void main(String... args) {
        Date date = new Date(System.currentTimeMillis());

        // Convert SQL Date object to OffsetDateTime object
        LocalDate localDate = date.toLocalDate();
        OffsetDateTime offsetDateTime = localDate.atTime(OffsetTime.now());

        System.out.println("SQL Date: " + date);
        System.out.println("OffsetDateTime: " + offsetDateTime);
    }
}
The output as below.
SQL Date: 2022-05-23
OffsetDateTime: 2022-05-23T21:36:30.156699400+07:00

Happy Coding 😊

Java Convert SQL Date to ZonedDateTime

Java Convert SQL Date to Calendar

Java Convert SQL Date to GregorianCalendar

Java Convert SQL Date to Instant

Java Convert LocalDate to SQL Date

Java Convert Instant to SQL Date

Java Convert LocalDateTime to SQL Date

Java Convert ZonedDateTime to SQL Date

Java Convert OffsetDateTime to SQL Date

Java Convert Date to SQL Date

Java Convert Calendar to SQL Date

Java Convert GregorianCalendar to SQL Date

Java Convert SQL Date to LocalDate

Java Convert SQL Date to LocalDateTime