Introduction
In this lab, you will learn how to use the now(Clock) method to generate local date based on zone across the world. You will learn the syntax, parameters, and returns of the method. This lab assumes you have a basic understanding of Java programming language.
Import the necessary packages
Import the java.time package in your code by adding the following line at the beginning of the DateDemo.java file.
import java.time.*;
Create a main() method
Create a main() method in your code as shown below.
public static void main(String[] args) {
}
Generate current date based on UTC time-zone
Use systemUTC() method of Clock class to generate current date based on UTC time-zone as shown below.
LocalDate localDate = LocalDate.now(Clock.systemUTC());
System.out.println("Current date based on UTC time-zone: " + localDate);
Generate current date based on system default clock
Use systemDefaultZone() method of Clock class to generate the current date based on the system default clock as shown below.
LocalDate localDate1 = LocalDate.now(Clock.systemDefaultZone());
System.out.println("Current date based on System Default Zone: " + localDate1);
Compile and run the code
Save the DateDemo.java file and open the terminal. Navigate to the ~/project directory and run the following commands to compile and run the code.
javac DateDemo.java
java DateDemo
Output
The output of the program should be displayed on the terminal as shown below.
Current date based on UTC time-zone: 2022-11-08
Current date based on System Default Zone: 2022-11-08
Summary
In this lab, we have learned how to use Java LocalDate now(Clock) method to get the current date and time based on a specified clock. We have seen examples of generating the current date based on UTC time-zone and system default clock. Now you can use this method to get the current date and time based on your desired clock.



