Introduction
The Java LocalDate class was introduced in Java 8 to represent a date without a time-zone. It provides various methods to perform operations on date objects such as adding or subtracting days, months, and years. One of these useful methods is the now(ZoneId) method which returns the current date based on a specified time-zone.
Create a Java file
Create a new Java file named LocalDateNowZoneId.java in the ~/project directory.
cd ~/project
touch LocalDateNowZoneId.java
Import the required packages
To use the LocalDate class and the ZoneId class, we need to import the java.time.LocalDate and java.time.ZoneId packages.
import java.time.LocalDate;
import java.time.ZoneId;
Get the current date with default system time-zone
To get the current date with default system time-zone, we can use the now() method of the LocalDate class. We also use the systemDefault() method of ZoneId to get the default system time-zone.
LocalDate localDate = LocalDate.now(ZoneId.systemDefault());
System.out.println("Current date with default system time-zone: " + localDate);
Get the current date with a specified time-zone
If we want to get the current date with a specified time-zone, we can pass the time-zone as an argument to the now() method. In this example, we pass the time-zone "Asia/Tokyo" to get the current date in Tokyo time-zone.
LocalDate localDate = LocalDate.now(ZoneId.of("Asia/Tokyo"));
System.out.println("Current date in Tokyo time-zone: " + localDate);
Get available time-zones
To display the available time-zones, we can use the getAvailableZoneIds() method of the ZoneId class.
System.out.println("Available time-zones:");
ZoneId.getAvailableZoneIds().forEach(System.out::println);
Compile and run the code
You can compile and run the code using the javac and java commands in the terminal.
javac LocalDateNowZoneId.java
java LocalDateNowZoneId
Summary
In this lab, we learned how to use the Java LocalDate now(ZoneId) method to obtain the current date from the system clock in the specified time-zone. We also learned how to get the available time-zones and how to use these time-zones in our code.



