Clock withZone() method in Java

Java 8ProgrammingObject Oriented Programming

A clock copy of the clock object can be obtained using the method withZone() in Clock Class in Java. This method is used on a clock object to obtain a clock copy. The withZone() method requires a single parameter i.e. the zone that is required to change the time zone. Also, it returns the clock copy of the clock object with the required time zone.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.time.*;
public class Demo {
   public static void main(String[] args) {
      Clock c1 = Clock.systemDefaultZone();
      ZoneId zone = ZoneId.of("Australia/Melbourne");
      Clock c2 = c1.withZone(zone);
      System.out.println("The Zone is: " + c2.getZone());
   }
}

Output

The Zone is: Australia/Melbourne

Now let us understand the above program.

A clock copy i.e. c2 of the clock object c1 is obtained using the method withZone(). Then the getzone() method is used to print the zone details. A code snippet that demonstrates this is as follows −

Clock c1 = Clock.systemDefaultZone();
ZoneId zone = ZoneId.of("Australia/Melbourne");
Clock c2 = c1.withZone(zone);
System.out.println("The Zone is: " + c2.getZone());
raja
Published on 27-Mar-2019 18:16:41
Advertisements