Java Clock

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Java Clock class

Java Clock class is used to provide an access to the current instant, date and time using a time zone. It inherits the Object class.


Java Clock class declaration

Let's see the declaration of java.time.Clock class.

  1. public abstract class Clock extends Object  

Methods of Java Clock

Method

Description

abstract ZoneId getZone()

It is used to get the time-zone being used to create dates and times.

abstract Instant instant()

It is used to get the current instant of the clock.

static Clock offset(Clock baseClock, Duration offsetDuration)

It is used to obtain a clock that returns instants from the specified clock with the specified duration added

static Clock systemDefaultZone()

It is used to obtain a clock that returns the current instant using the best available system clock, converting to date and time using the default time-zone.

static Clock systemUTC()

It is used to obtain a clock that returns the current instant using the best available system clock, converting to date and time using the UTC time zone.

Java Clock class Example: getZone()

  1. import java.time.Clock;  
  2. public class LocalDateExample {  
  3.   public static void main(String[] args) {  
  4.     Clock c = Clock.systemDefaultZone();      
  5.     System.out.println(c.getZone());  
  6.   }  
  7. }  

Output:

Asia/Calcutta

Java Clock class Example: instant()

  1. import java.time.Clock;  
  2. public class LocalDateExample {  
  3.   public static void main(String[] args) {  
  4.     Clock c = Clock.systemUTC();  
  5.     System.out.println(c.instant());  
  6.   }  
  7. }  

Output:

2017-01-14T07:11:07.748Z

Java Clock class Example: systemUTC()

  1. import java.time.Clock;  
  2. public class LocalDateExample {  
  3.   public static void main(String[] args) {  
  4.     Clock c = Clock.systemUTC();  
  5.     System.out.println(c.instant());  
  6.   }  
  7. }  

Output:

2017-01-14T07:11:07.748Z

Java Clock class Example: offset()

  1. import java.time.Clock;  
  2. import java.time.Duration;  
  3. public class LocalDateExample {  
  4.   public static void main(String[] args) {  
  5.     Clock c = Clock.systemUTC();  
  6.     Duration d = Duration.ofHours(5);  
  7.     Clock clock = Clock.offset(c, d);    
  8.     System.out.println(clock.instant());  
  9.   }  
  10. }  

Output:

2017-01-14T14:15:25.389Z