How do you use ZonedDateTime with a simple code example?

ZonedDateTime is a class in Java that represents a date-time with a time zone, allowing you to handle the date and time consistently across different regions. It is part of the Java Time API, introduced in Java 8, which helps in dealing with date and time more effectively.

Below is a simple example of how to use ZonedDateTime in Java:

import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; public class ZonedDateTimeExample { public static void main(String[] args) { // Create a ZonedDateTime instance for the current date and time ZonedDateTime currentDateTime = ZonedDateTime.now(); // Format the date and time DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss Z"); String formattedDateTime = currentDateTime.format(formatter); // Print the current date and time System.out.println("Current date and time: " + formattedDateTime); } }

ZonedDateTime Java Date and Time API Java 8 Time Zone DateTimeFormatter