Java Convert Date to OffsetDateTime

Tags: Java OffsetDateTime Java Date Java 8

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

Table of contents

  1. How to convert Date to OffsetDateTime in Default System Time Zone
  2. How to convert Date to OffsetDateTime in UTC Time Zone

How to convert Date to OffsetDateTime in Default System Time Zone

In Java program, with a given Date object we can follow these steps to convert it to an OffsetDateTime object in system default time zone.

  • Step 1: convert Date object to Instant using Date.toInstant() method.
  • Step 2: create new OffsetDateTime from an Instant using Instant.atOffset() method with a ZoneOffset object from system default time zone.

ConvertDateToOffsetDateTimeExample1.java

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

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

        Instant instant = date.toInstant();
        ZoneOffset zoneOffset = ZoneId.systemDefault().getRules().getOffset(Instant.now());
        OffsetDateTime offsetDateTime = instant.atOffset(zoneOffset);

        System.out.println("Date: " + date);
        System.out.println("OffsetDateTime: " + offsetDateTime);
    }
}
The output as below.
Date: Sat May 14 15:59:51 ICT 2022
OffsetDateTime: 2022-05-14T15:59:51.360+07:00

How to convert Date to OffsetDateTime in UTC Time Zone

In the following Java program we learn convert Date object to an OffsetDateTime object in UTC time zone.

ConvertDateToOffsetDateTimeExample2.java

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

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

        Instant instant = date.toInstant();
        OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.UTC);

        System.out.println("Date: " + date);
        System.out.println("OffsetDateTime: " + offsetDateTime);
    }
}
The output as below.
Date: Sat May 14 16:00:18 ICT 2022
OffsetDateTime: 2022-05-14T09:00:18.891Z

Happy Coding 😊

Java Convert OffsetDateTime to Epoch Seconds

Java Convert OffsetDateTime to ZoneOffset

Java Convert OffsetDateTime to LocalDate

Java Convert OffsetDateTime to LocalTime

Java Convert OffsetDateTime to LocalDateTime

Java Convert OffsetDateTime to ZonedDateTime

Java Convert OffsetDateTime to Instant

Java Convert OffsetDateTime to Date

Java Convert OffsetDateTime to Calendar

Java Convert OffsetDateTime to OffsetTime

Java Convert OffsetDateTime to String

Java Convert String to OffsetDateTime

Java Convert Calendar to OffsetDateTime