Java Clock.withZone() method with examples
In this tutorial, we will learn about the Clock.withZone() method in Java with example.
To use this method we have to import java.time package.
The java.time.Clock.withZone() method returns a replica of this clock with a special time-zone.
This method takes a compulsory parameter zone of type ZoneId, during which it’s required to vary the time-zone.
This method returns a clock copy of the clock object on where this method is applied with a special time-zone that is passed as parameter.
To use the clockZone() method we have to import java.time.Clock and java.time.ZoneId.
EXAMPLE CODE1:-
In the program to use the clockZone() method first we have to import java.time.Clock and java.time.ZoneId.
// In this program we will learn clock.withZone. //import package import java.time.Clock; import java.time.ZoneId; // main class public class ClockZone { public static void main(String[] args) { Clock clk = Clock.systemUTC(); Clock clck = clock.withZone(ZoneId.systemDefault()); System.out.println("Clk : " + clk.instant()); System.out.println("Clck : " + clck.instant()); } }
OUTPUT:-
Clk : 2020-04-22T15:51:16.526694900Z Clck : 2020-04-22T15:51:16.542381Z
EXAMPLE CODE 2:-
In this program, we will first import java.time.*. Here ‘*’ means we will import all the functions of java.time.
//import all the functions of java.time import java.time.*; public class ClockZone { //main function public static void main(String[] args) { Clock bk = Clock.systemDefaultZone(); ZoneId z = ZoneId.of("Asia/Calcutta"); Clock cWZ = bk.withZone(z); System.out.println("the zone is:" + cWZ.getZone()); } }
And the output of the program when we run it will be the time Zone.
the zone is:Asia/Calcutta
So we see that the method is successfully able to show the time zone.
Leave a Reply