Java Convert Date to OffsetDateTime in UTC

Tags: Java Date Java OffsetDateTime Java 8 UTC

In this Java core tutorial we learn how to convert a java.util.Date object to a java.time.OffsetDateTime object in UTC time zone offset.

How to convert Date to UTC OffsetDateTime in Java

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

  • Step 1: use the Date.toInstant() method to convert the Date object to an Instant object.
  • Step 2: use the Instant.atOffset(ZoneOffset offset) method to convert the Instant object of step 1 to a OffsetDateTime object in UTC time zone offset.

ConvertDateToUTCOffsetDateTimeExample1.java

import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Date;

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

        // Convert Date object to UTC OffsetDateTime object
        Instant instant = date.toInstant();
        OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.UTC);

        System.out.println("Date: " + date);
        System.out.println("UTC OffsetDateTime: " + offsetDateTime);
    }
}
The output as below.
Date: Tue May 24 21:41:09 ICT 2022
UTC OffsetDateTime: 2022-05-24T14:41:09.485Z

Happy Coding 😊

Java Convert LocalDate to Date in UTC

Java Convert LocalDateTime to Date in UTC

Java Convert Date to LocalDate in UTC

Java Convert Date to LocalDateTime in UTC

Java Convert Date to ZonedDateTime in UTC