Instant atZone() method in Java with Examples
The atZone(ZoneId zone) method of Instant class is used to combine this instant with a time-zone whose ZoneId is given as parameter to create an ZonedDateTime object. This method takes ZoneId as a parameter and combines the time-zone with this instant after operation returns a ZonedDateTime object. If the instant is too large to fit into a zoned date-time then this method will throw an exception. This method is same as ZonedDateTime.ofInstant(this, zone).
Syntax:
public ZonedDateTime atZone(ZoneId zone)
Parameters: This method accepts one parameter zone which is the zone to combine to this instant object. It should not be null.
Return Value: This method returns a ZonedDateTime which is the combination of current zone of Instant and the zone passed as the parameter.
Exception: This method throws DateTimeException if the instant is too large to fit into a zoned date-time.
Below programs illustrate the Instant.atZone() method:
Program 1:
// Java program to demonstrate // Instant.atZone() method import java.time.*; public class GFG { public static void main(String[] args) { // create an instance object Instant instant = Instant.parse( "2018-10-20T16:55:30.00Z" ); // print Instant Value System.out.println( "Instant: " + instant); // create ZoneId object ZoneId zone = ZoneId.of( "Europe/Paris" ); // apply atZone method of Instant class ZonedDateTime result = instant.atZone(zone); // print results System.out.println( "ZonedDateTime: " + result); } } |
Instant: 2018-10-20T16:55:30Z ZonedDateTime: 2018-10-20T18:55:30+02:00[Europe/Paris]
Program 2:
// Java program to demonstrate // Instant.atZone() method import java.time.*; public class GFG { public static void main(String[] args) { // create an instance object Instant instant = Instant.parse( "2018-11-18T06:55:30.00Z" ); // print Instant Value System.out.println( "Instant: " + instant); // create ZoneId object ZoneId zone = ZoneId.of( "Asia/Aden" ); // apply atZone method ZonedDateTime result = instant.atZone(zone); // print results System.out.println( "ZonedDateTime: " + result); } } |
Instant: 2018-11-18T06:55:30Z ZonedDateTime: 2018-11-18T09:55:30+03:00[Asia/Aden]
Program 3:
// Java program to demonstrate // Instant.atZone() method import java.time.*; public class GFG { public static void main(String[] args) { // create an instance object Instant instant = Instant.now(); // print Instant Value System.out.println( "Instant: " + instant); // create ZoneId object ZoneId zone = ZoneId.of( "Pacific/Midway" ); // apply atZone method ZonedDateTime result = instant.atZone(zone); // print results System.out.println( "ZonedDateTime: " + result); } } |
Instant: 2018-11-22T08:11:48.029Z ZonedDateTime: 2018-11-21T21:11:48.029-11:00[Pacific/Midway]
References: https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#atZone(java.time.ZoneId)
Please Login to comment...