Java Clock Class | withZone() Method with Example

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

Clock Class withZone() method

  • withZone() method is available in java.time package.
  • withZone() method is used to clone this Clock object but with a different zone.
  • withZone() 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.
  • withZone() method does not throw an exception at the time of representing Clock.

Syntax:

    public static Clock withZone(ZoneId zo);

Parameter(s):

  • ZoneId zo – represents the zone to convert the clock instant to date: time.

Return value:

The return type of this method is Clock, it returns this Clock but available with the given zone.

Example:

// Java program to demonstrate the example 
// of withZone(ZoneId zo) method of Clock

import java.time.*;

public class WithZoneOfClock {
    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 
        Clock cl1 = Clock.system(zone_1);
        Clock cl2 = Clock.system(zone_2);

        // clones this Clock (cl1)
        // but available with the given time-zone
        // zone_2
        Clock with_zone = cl1.withZone(zone_2);

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

        System.out.println();

        // clones this Clock (cl2)
        // but available with the given time-zone
        // zone_1
        with_zone = cl2.withZone(zone_1);

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

Output

cl1.instant(): 2020-05-13T22:05:38.373623Z
with_zone.instant(): 2020-05-13T22:05:38.421565Z

cl2.instant(): 2020-05-13T22:05:38.422633Z
with_zone.instant(): 2020-05-13T22:05:38.423364Z


Comments and Discussions!

Load comments ↻





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