Clock class is an abstraction for the real-world clock.
It provides access to the current instant, date, and time in a time zone.
You can obtain a clock for the system default time zone.
Clock clock = Clock.systemDefaultZone();
You can also get a clock for a specified time zone.
Get a clock for Asia/Kolkata time zone
ZoneId asiaKolkata = ZoneId.of("Asia/Kolkata");
Clock clock2 = Clock.system(asiaKolkata);
To get the current instant, date, and time from a clock, you can use the now(Clock c) method of the datetime related classes.
import java.time.Clock; import java.time.Instant; import java.time.LocalDate; import java.time.ZonedDateTime; public class Main { public static void main(String[] args) { // Get the system default clock Clock clock = Clock.systemDefaultZone(); System.out.println(clock);/*from w w w . j a va 2 s .c om*/ // Get the current instant of the clock Instant instant1 = clock.instant(); System.out.println(instant1); // Get the current instant using the clock and the Instant class Instant instant2 = Instant.now(clock); System.out.println(instant2); // Get the local date using the clock LocalDate ld = LocalDate.now(clock); System.out.println(ld); // Get the zoned datetime using the clock ZonedDateTime zdt = ZonedDateTime.now(clock); System.out.println(zdt); } }
now() method without arguments in all date, time, and datetime classes uses the system default clock for the default time zone. The following two statements use the same clock:
LocalTime lt1 = LocalTime.now(); LocalTime lt2 = LocalTime.now(Clock.systemDefaultZone());
systemUTC() method from Clock class returns a clock for the UTC time zone.
You can obtain the system default time zone using the Clock class as follows:
ZoneId defaultZone = Clock.systemDefaultZone().getZone();