June 25, 2022

Convert LocalDateTime to OffsetDateTime in Java

This tutorial shows how to convert java.time.LocalDateTime to java.time.OffsetDateTime in Java.

OffsetDateTime in Java

OffsetDateTime is a date-time with an offset from UTC/Greenwich in the ISO-8601 calendar system, such as 2020-12-07T11:45:20+05:30.

Convert LocalDateTime to OffsetDateTime Java Program

If you have a LocalDateTime instance you just need to combine it with an offset to create an OffsetDateTime.

If you want to combine offset for the same default locale for which you have a LocalDateTime then you can do it like this.

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;

public class LocalToOffset {
  public static void main(String[] args) {
    LocalDateTime localDateTime = LocalDateTime.now();
    System.out.println("LocalDateTime is: " + localDateTime);
    ZoneOffset zoneOffSet = OffsetDateTime.now().getOffset();
    System.out.println("ZoneOffset is: " + zoneOffSet.toString());
    OffsetDateTime offsetDateTime = localDateTime.atOffset(zoneOffSet);
    System.out.println("OffsetDateTime is: " + offsetDateTime);
  }
}
Output
LocalDateTime is: 2020-12-09T16:36:36.616370500
ZoneOffset is: +05:30
OffsetDateTime is: 2020-12-09T16:36:36.616370500+05:30

If you want to combine Zoneoffset for any specific zone id then you can get the ZonedDateTime by passing the zoneId and OffsetDateTime from that ZonedDateTime.

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;

public class LocalToOffset {
  public static void main(String[] args) {
    ZoneId zoneId = ZoneId.of("America/Chicago");
    LocalDateTime localDateTime = LocalDateTime.now();
    System.out.println("LocalDateTime is: " + localDateTime);
    ZonedDateTime zonedDateTime = localDateTime.atZone(zoneId);
    System.out.println("ZonedDateTime is: " + zonedDateTime);
    OffsetDateTime offsetDateTime = zonedDateTime.toOffsetDateTime();
    System.out.println("OffsetDateTime is: " + offsetDateTime);
    
    // Same thing can also be done in a single line
    offsetDateTime = localDateTime.atZone(ZoneId.of("America/Chicago")).toOffsetDateTime();
  }
}
Output
LocalDateTime is: 2020-12-09T17:08:14.425502600
ZonedDateTime is: 2020-12-09T17:08:14.425502600-06:00[America/Chicago]
OffsetDateTime is: 2020-12-09T17:08:14.425502600-06:00

That's all for the topic Convert LocalDateTime to OffsetDateTime in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment