Java Convert OffsetDateTime to Another Time Zone
Tags: Java OffsetDateTime Java 8 Java ZoneOffset Java ZoneId
In this Java core tutorial we learn how to convert a java.time.OffsetDateTime object from a specified time zone to another time zone in Java programming language.
How to convert OffsetDateTime to Another Time Zone in Java
In Java, with a given OffsetDateTime object in specified time zone we can use the OffsetDateTime.withOffsetSameInstant(ZoneOffset offset) method to get a new OffsetDateTime object in another time zone.
In the following example Java code we show how to use the OffsetDateTime.withOffsetSameInstant(ZoneOffset offset) method convert OffsetDateTime object in Vietnam time zone to Australia/Sydney time zone.
ConvertOffsetDateTimeToAnotherTimeZoneExample1.java
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
public class ConvertOffsetDateTimeToAnotherTimeZoneExample1 {
public static void main(String... args) {
OffsetDateTime vietnamOffsetDateTime = OffsetDateTime.parse("2022-05-22T16:30:40+07:00");
ZoneOffset sydneyZoneOffset = ZoneId.of("Australia/Sydney").getRules().getOffset(Instant.now());
OffsetDateTime australiaOffsetDateTime = vietnamOffsetDateTime.withOffsetSameInstant(sydneyZoneOffset);
System.out.println("Source OffsetDateTime (Vietnam time zone): " + vietnamOffsetDateTime);
System.out.println("Destination OffsetDateTime (Australia/Sydney time zone): " + australiaOffsetDateTime);
}
}
Source OffsetDateTime (Vietnam time zone): 2022-05-22T16:30:40+07:00
Destination OffsetDateTime (Australia/Sydney time zone): 2022-05-22T19:30:40+10:00
Happy Coding 😊