java.time.Clock Class in Java
Java Clock class is present in java.time package. It was introduced in Java 8 and provides access to current instant, date, and time using a time zone.
The use of the Clock class is not mandatory because all date-time classes also have a now() method that uses the system clock in the default time zone. The main purpose of using Clock class is to plug an alternate clock wherever required. Applications use an object to obtain the current time rather than a static method. This makes the testing easy. We can pass a Clock as an argument to a method that requires a current instant.
public abstract class Clock extends Object
It is an abstract class, so we can’t instantiate it, But we can use several static methods to access its instance.
public static Clock systemUTC()
This method returns a Clock instance of the current instant in the UTC time zone. This is best when you need a current instant without a date or time.
UTC time = 2021-02-07T16:16:43.863267Z
public static Clock systemDefaultZone()
This method returns a Clock instance of the current instant using the default time zone of the system.
SystemClock[Etc/UTC] Time Zone : Etc/UTC
|fixed(Instant fixedInstant, ZoneId zone)||Used to get a Clock which always returns the same instant.|
|getZone()||Returns the time zone of the given clock.|
|instant()||Used to get current instant of the clock.|
|millis()||Returns current millisecond instant of the clock.|
|offset(Clock baseClock, Duration offsetDuration)||Returns a Clock that returns instant from the specified clock with the specified duration added.|
|system(ZoneId zone)||Returns a Clock object of current instant for the specified zone id.|
|systemDefaultZone()||Returns a Clock instance of the current instant using the default time zone of the system.|
|systemUTC()||Returns a Clock instance of current instant in UTC time zone.|
|tick(Clock baseClock, Duration tickDuration)||Returns instants from the specified base clock truncated to the nearest occurrence of the specified duration.|
|tickMinutes(ZoneId zone)||Returns a Clock object of current instant ticking in whole minutes for the given time zone.|
|tickSeconds(Zoneid zone)||Returns a Clock object of current instant ticking in whole seconds for the given time zone.|
|withZone(ZoneId zone)||Create a copy of the clock with the different time zone.|
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.