Java Clock withZone() method in Java with Examples
The java.time.Clock.withZone(ZoneId zone) method is a method of Clock class which returns a clock copy of clock object on which this method is applied, with a different time-zone. If there is a clock and it is required to change the zone of clock but not other properties, then withZone() method is used. This method takes zone as parameter which is the time-zone in which it is required to change. It returns the clock with zone, same as passed zone in parameter.
public abstract Clock withZone(ZoneId zone)
Parameter: This method takes a mandatory parameter zone of type ZoneId, in which it is required to change the time-zone.
Returns: This method returns a clock copy of clock object on which this method is applied, with a different time-zone passed as parameter.
Code: //Clock with default zone Clock clock1=Clock.systemUTC(); ZoneId zone = ZoneId.of("Asia/Calcutta"); Clock clock2 = clock1.withZone(zone); System.out.println(clock2.toString()); Output:: SystemClock[Asia/Calcutta] Explanation:: when withZone() is called for Clock object clock1 with zoneId "Asia/Calcutta", then the withZone() method will return a Clock whose Zone is "Asia/Calcutta".
Below programs illustrates withZone() method of java.time.Clock class:
Program 1: To create a clock with similar properties as First Clock but zoneId equal to “Asia/Calcutta” with the help of withZone().
ZonedDateTime of baseclock 2018-08-24T08:09:17.354Z ZonedDateTime of clockWithOtherZone 2018-08-24T13:39:17.539+05:30[Asia/Calcutta]
Program 2: Print the zoneId using getZone() for clock created by withZone().
baseclock Zone:Etc/UTC clockWithOtherZone Zone:Asia/Calcutta