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.
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024