How do I convert datetime between time zones?

The ZonedDateTime class is part of the Java Date-Time Package (java.time.*), released in Java 8 to address the shortcomings of the old date-time classes such as java.util.Date, java.util.Calendar, and java.util.SimpleDateFormat.

Some of the key features are:

  • It represents a date-time with a timezone in the ISO-8601 calendar system, such as ‘2007-12-03T10:15:30+01:00 Europe/Paris’.
  • It provides a lot of methods to play with year, month, day, hour, minute, second and nanosecond fields of the datetime.
  • It’s an immutable class, which is good for multithreaded environments.
  • It provides a fluent interface, which allows method calls to be chained.

Using Java java.time package (which is part of Java 8 and later), you can convert dates between time zones like this:

package org.kodejava.datetime;

import java.time.*;

public class ZonedDateTimeExample {
    public static void main(String[] args) {

        // Create a ZonedDateTime instance for the current date/time
        // in the current timezone
        ZonedDateTime now = ZonedDateTime.now();

        // Create a ZonedDateTime instance for the current date/time
        // in a different timezone
        ZonedDateTime nowInJakarta = now.withZoneSameInstant(ZoneId.of("Asia/Jakarta"));

        // Print the current date/time in the current timezone
        System.out.println("Current date/time: " + now);

        // Print the current date/time in the different timezone
        System.out.println("Current date/time in Jakarta: " + nowInJakarta);
    }
}

Output:

Current date/time: 2024-01-20T21:33:31.236022700+08:00[Asia/Makassar]
Current date/time in Jakarta: 2024-01-20T20:33:31.236022700+07:00[Asia/Jakarta]

The withZoneSameInstant method is used to adjust the date and time based on the timezone. It can be used to convert a datetime value to the datetime in another timezone.

This program will create a ZonedDateTime object representing the current date and time, and then create another ZonedDateTime object that represents the current date and time in Jakarta. Finally, it will print both dates to the console.

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.