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.
Syntax:
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.
Example:
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().
import java.time.*;
public class withZoneMethodDemo {
public static void main(String[] args)
{
Clock baseclock = Clock.systemUTC();
ZonedDateTime baseTime = baseclock
.instant()
.atZone(baseclock.getZone());
System.out.println( "ZonedDateTime of baseclock "
+ baseTime.toString());
ZoneId zone = ZoneId.of( "Asia/Calcutta" );
Clock clockWithOtherZone = baseclock.withZone(zone);
ZonedDateTime calcuttaTime = clockWithOtherZone
.instant()
.atZone(clockWithOtherZone.getZone());
System.out.println( "ZonedDateTime of clockWithOtherZone "
+ calcuttaTime.toString());
}
}
|
Output:
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().
import java.time.*;
public class withZoneMethodDemo {
public static void main(String[] args)
{
Clock baseclock = Clock.systemDefaultZone();
System.out.println( "baseclock Zone:"
+ baseclock.getZone());
ZoneId zone = ZoneId.of( "Asia/Calcutta" );
Clock clockWithOtherZone = baseclock.withZone(zone);
System.out.println( "clockWithOtherZone Zone:"
+ clockWithOtherZone.getZone());
}
}
|
Output:
baseclock Zone:Etc/UTC
clockWithOtherZone Zone:Asia/Calcutta
Reference:
https://docs.oracle.com/javase/8/docs/api/java/time/Clock.html#withZone-java.time.ZoneId-
Last Updated :
10 Dec, 2018
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...