Java ZonedDateTime
The Java ZonedDateTime class is an immutable and thread-safe class that represents a date-time with a time-zone. The ZonedDateTime class can be used to store all date and time fields, to a precision of nanoseconds, and a time-zone.
How to use
The ZonedDateTime class can be used to store information like- “22nd April 2019 at 10:30.40.123456789 +02:00 in the Asia/Calcutta time-zone”. Try the following examples to better understand –
Now example
The following example program shows how you can use the ZonedDateTime class to get the current date & time with the time zone.
import java.time.ZonedDateTime; public class ZonedDateTimeExample1 { public static void main(String[] args) { // Get instance of ZonedDateTime ZonedDateTime zonedDateTime = ZonedDateTime.now(); // Print current date & time with zone System.out.println(zonedDateTime); } }
Parsing example
The following example program shows how you can use parse() function to parse zoned date and time string.
import java.time.ZonedDateTime; public class ZonedDateTimeExample2 { public static void main(String[] args) { // Parse zoned date & time from string ZonedDateTime zonedDateTime = ZonedDateTime.parse("2019-05-07T14:43:38.848482200+05:30[Asia/Calcutta]"); // Print the zone System.out.println(zonedDateTime.getZone()); } }
Add/Subtract example
The following example program shows how you can use plus/minus function to add or subtract years with ZonedDateTime
import java.time.ZonedDateTime; public class ZonedDateTimeExample3 { public static void main(String[] args) { // Get instance of ZonedDateTime ZonedDateTime zonedDateTime = ZonedDateTime.now(); System.out.println(zonedDateTime); // Add 5 years zonedDateTime = zonedDateTime.plusYears(5); System.out.println(zonedDateTime); // Subtract 2 years zonedDateTime = zonedDateTime.minusYears(2); System.out.println(zonedDateTime); } }
Format example
The following example program shows how you can use DateTimeFormatter with ZonedDateTime
import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; public class ZonedDateTimeExample4 { public static void main(String[] args) { // Get instance of ZonedDateTime ZonedDateTime zonedDateTime = ZonedDateTime.now(); // Format zonedDateTime, get Local date only String format = zonedDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE); System.out.println(format); } }