Monday, September 3, 2018

java8 - java.time.Clock Class Beginner guide with examples

java.time.Clock Class 

In this blog, We are going to cover Clock class with examples.
Clock class was added in java8. It is used to represent Date, Time and Timezone with 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 OffsetClock,SystemClock,TickClock,FixedClock
It is immutable and threads safe
This class is a parameter for most of the classes available in java.time package

Clock Object Creation

Since Clock is an abstract class, We can create an instance using four classes FixedClock, OffsetClock, SystemClock, and TickClock.

systemDefaultZone() methods

 It is a Static method to create a Clock instance with default current system timazone
Clock clock = Clock.systemDefaultZone();
System.out.println(clock); //SystemClock[Asia/Calcutta]

systemUTC method examples 

systemUTC() is a static method that returns Instant time in clock instance.
Clock clock = Clock.systemUTC();
System.out.println(clock.instant()); //2018-09-03T08:29:43.823974100Z

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

system 

This 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]

Related article


EmoticonEmoticon