package org.code2care.java.examples;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class JavaTimeZoneConverter {
public static void main(String[] args) {
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss zzz");
LocalDateTime localDateTime = LocalDateTime.now();
ZoneId utcZone = ZoneId.of("UTC");
ZoneId targetZoneChicago = ZoneId.of("America/Chicago");
ZoneId targetZoneLondon = ZoneId.of("Europe/London");
ZoneId targetZoneNewYork = ZoneId.of("America/New_York");
ZonedDateTime convertedDateTimeUTC = ZonedDateTime.of(localDateTime, utcZone).withZoneSameInstant(utcZone);
ZonedDateTime convertedDateTimeChicago = ZonedDateTime.of(localDateTime, utcZone).withZoneSameInstant(targetZoneChicago);
ZonedDateTime convertedDateTimeLondon = ZonedDateTime.of(localDateTime, utcZone).withZoneSameInstant(targetZoneLondon);
ZonedDateTime convertedDateTimeNewYork = ZonedDateTime.of(localDateTime, utcZone).withZoneSameInstant(targetZoneNewYork);
System.out.println("UTC/GMT Time: " + convertedDateTimeUTC.format(dateTimeFormatter));
System.out.println("Chicago Time: " + convertedDateTimeChicago.format(dateTimeFormatter));
System.out.println("London Time: " + convertedDateTimeLondon.format(dateTimeFormatter));
System.out.println("New York Time: " + convertedDateTimeNewYork.format(dateTimeFormatter));
}
}
Output:
We have made use of the ZonedDateTime class, it allows to represent a date and time with a time zone.
We do the conversion using ZonedDateTime.of() with LocalDateTime object and the UTC time zone, and finally use withZoneSameInstant() to convert the date and time to the target time zone.
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!