java8 - java.time.Clock Class Beginner guide with examples
It cover the Clock class with examples.
java.time.Clock Class in java8
Clock
class was added in java8. It is used to represent Date
, Time
, and Timezone with the best available Clock.
Clock
class is an abstract class, instances cannot be created. It provides Factory static methods to create Instance of Clock instances. It provides static method - OffsetClock
,SystemClock
,TickClock
,FixedClock
It is immutable and threads safe.
This class is an input parameter for most of the classes available in the java.time
package.
How to create a Clock Object?
Since Clock
is an abstract class, We can create an instance using four classes FixedClock
, OffsetClock
, SystemClock
, and TickClock
.
There are multiple ways we can create a Clock object.
- using systemDefaultZone() methods
It is a Static method to create a Clock
instance with the default current system timezone.
Clock clock = Clock.systemDefaultZone();
System.out.println(clock); //SystemClock[Asia/Calcutta]
- using systemUTC method examples
systemUTC()
is a static method that returns Instant time in a clock instance.
Clock clock = Clock.systemUTC();
System.out.println(clock.instant()); //2018-09-03T08:29:43.823974100Z
- using mills method Example
This method returns the epcoh mill seconds of the current instance clock class.
Clock clock = Clock.systemDefaultZone();
System.out.println(clock.millis()); // 1535963292307
using system method
It is a static method used to create a Clock class with a given timezone.
Clock clock = Clock.system(ZoneId.of("America/Chicago"));
System.out.println(clock); //SystemClock[America/Chicago]
Conclusion
In this tutorial, Learned java.time.Clock class in java8 and discussed multiple ways to create a Clock object.