Java 8: Convert Date between Time Zones Example


Example:
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:

UTC/GMT Time: 24-06-2023 16:44:47 UTC
Chicago Time: 24-06-2023 11:44:47 CDT
London Time: 24-06-2023 17:44:47 BST
New York Time: 24-06-2023 12:44:47 EDT


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.

-

Facing issues? Have Questions? Post them here! I am happy to answer!


Author: Rakesh
Author Info:

Rakesh is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

Copyright © Code2care 2023 | Privacy Policy | About Us | Contact Us | Sitemap