Java 8 Clock offset() method with Examples
Java Clock class is part of Date Time API, java.time.Clock, of Java. The Java Date Time API was added from Java version 8.
The offset() method is a static method of Clock class which returns a clock with instant equal to the sum of the instants of clock passed as parameter and specific Offset duration. If the duration added is positive, then the returned clock represents the instant of the clock later by the specified duration from base clock. If the duration added is negative, then the returned clock is earlier than the date and time of the base clock. A duration of Zero does nothing to the base clock and returns the base clock.
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.
If the base clock is immutable, thread-safe and Serializable then returned clock is also immutable, thread-safe and Serializable.
public static Clock offset(Clock baseClock, Duration offsetDuration)
Parameters: This method accepts two mandatory parameters:
- baseclock – a clock for adding duration. It cannot be a null value.
- offsetDuration – duration to add with baseClock. It cannot be a null value as well.
Return Value: This method returns a clock with instant equal to the sum of instants of clock passed as parameter and Specific Offset duration.
Below programs illustrates offset(Clock baseClock, Duration offsetDuration) method of java.time.Clock class:
Program 1: When offset is passed as hours.
Real clock instant is 2018-08-21T09:43:13.519Z New clock instant with Duration = 0 is 2018-08-21T09:43:13.785Z New clock instant with Duration = 24hours is 2018-08-22T09:43:13.785Z New clock instant with Duration = -24hours is 2018-08-20T09:43:13.785Z
Program 2: When offset is passed as seconds and minutes.
Real clock instant is 2018-08-21T09:43:18.921Z Time after 50 second later than real Clock is 2018-08-21T09:44:08.969Z Time after 30 minutes later than real Clock is 2018-08-21T10:13:18.969Z