Java Convert LocalDateTime to Another Time Zone
Tags: Java LocalDateTime Java 8 Java ZoneId
In this Java core tutorial we learn how to convert a java.time.LocalDateTime object from a specified time zone to another time zone in Java programming language.
How to convert LocalDateTime to Another Time Zone in Java
In Java, with a given LocalDateTime object we can follow these steps to convert it from a specified time zone to another time zone.
- Step 1: Convert LocalDateTime object to ZonedDateTime object in source time zone using ZonedDateTime.of(LocalDateTime localDateTime, ZoneId zone) static method.
- Step 2: Convert the above ZonedDateTime object to destination time zone using ZonedDateTime.withZoneSameInstant(ZoneId zone) method.
- Step 3: Using ZonedDateTime.toLocalDateTime() method to get the final result which is a LocalDateTime object in destination time zone.
In the following example Java code we show how to use the above steps to convert a LocalDateTime object from America/Los_Angeles time zone to Europe/Paris time zone.
ConvertLocalDateTimeToAnotherTimeZoneExample1.java
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class ConvertLocalDateTimeToAnotherTimeZoneExample1 {
public static void main(String... args) {
LocalDateTime localDateTime = LocalDateTime.parse("2022-05-22T14:30:40");
ZoneId fromZoneId = ZoneId.of("America/Los_Angeles");
ZonedDateTime losAngelesZonedDateTime = ZonedDateTime.of(localDateTime, fromZoneId);
ZoneId toZoneId = ZoneId.of("Europe/Paris");
ZonedDateTime parisZonedDateTime = losAngelesZonedDateTime.withZoneSameInstant(toZoneId);
LocalDateTime parisLocalDateTime = parisZonedDateTime.toLocalDateTime();
System.out.println("Source LocalDateTime (in America/Los_Angeles time zone): " + localDateTime);
System.out.println("Output LocalDateTime (in Europe/Paris time zone): " + parisLocalDateTime);
}
}
Source LocalDateTime (in America/Los_Angeles time zone): 2022-05-22T14:30:40
Output LocalDateTime (in Europe/Paris time zone): 2022-05-22T23:30:40
Happy Coding 😊