Java Clock Class | offset() Method with Example

Clock Class offset() method: Here, we are going to learn about the offset() method of Clock Class with its syntax and example.
Submitted by Preeti Jain, on May 13, 2020

Clock Class offset() method

  • offset() method is available in java.time package.
  • offset() method is used to generate a new Clock from the given base clock with added the given Duration.
  • offset() method is a static method, it is accessible with the class name and if we try to access the method with the class object then we will not get an error.
  • offset() method does not throw an exception at the time of representing Clock.

Syntax:

    public static Clock offset(Clock base_cl, Duration off);

Parameter(s):

  • Clock base_cl – represents the base clock in which to add the given duration.
  • Duration off – represents the offset to add to the given base clock (base_cl).

Return value:

The return type of this method is Clock, it returns the Clock object that is available with added the given offset.

Example:

// Java program to demonstrate the example 
// of offset(Clock base_cl, Duration off) method of Clock

import java.time.*;

public class OffsetOfClock {
    public static void main(String args[]) {
        // Instantiates two ZoneId for Accra and Asmara
        ZoneId zone_1 = ZoneId.of("Africa/Accra");
        ZoneId zone_2 = ZoneId.of("Africa/Asmara");

        // Initialize two Clock objects 
        // and one Duration
        Clock cl1 = Clock.system(zone_1);
        Clock cl2 = Clock.system(zone_2);
        Duration offset = Duration.ofMinutes(20);

        // generates a new Clock from the
        // given clock(cl1) with the given duration added
        Clock cl_offset = cl1.offset(cl1, offset);

        // Display cl1 and cl_offset instant
        System.out.println("cl1.instant(): " + cl1.instant());
        System.out.println("cl_offset.instant(): " + cl_offset.instant());

        System.out.println();

        // generates a new Clock from the
        // given clock(cl2) with the given duration added
        cl_offset = cl2.offset(cl2, offset);

        // Display cl2 and cl_offset instant
        System.out.println("cl2.instant(): " + cl2.instant());
        System.out.println("cl_offset.instant(): " + cl_offset.instant());
    }
}

Output

cl1.instant(): 2020-05-13T19:04:36.242559Z
cl_offset.instant(): 2020-05-13T19:24:36.322896Z

cl2.instant(): 2020-05-13T19:04:36.324623Z
cl_offset.instant(): 2020-05-13T19:24:36.327267Z


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.