Java 8 examples to show you how to convert from Instant
to ZonedDateTime
1. Instant -> ZonedDateTime
Example to convert a Instant
UTC+0 to a Japan ZonedDateTime
UTC+9
InstantZonedDateTime1.java
package com.favtuts.time; import java.time.Instant; import java.time.ZoneId; import java.time.ZonedDateTime; public class InstantToZonedDateTime { public static void main(String[] args) { convertInstantToZonedDateTime(); } static void convertInstantToZonedDateTime() { // Z = UTC+0 Instant instant = Instant.now(); System.out.println("Instant : " + instant); // Japan = UTC+9 ZonedDateTime jpTime = instant.atZone(ZoneId.of("Asia/Tokyo")); System.out.println("ZonedDateTime JP: " + jpTime); System.out.println("OffSet JP: " + jpTime.getOffset()); // Vietnam = UTC+7 ZonedDateTime vnTime = instant.atZone(ZoneId.of("Asia/Ho_Chi_Minh")); System.out.println("ZonedDateTime VN: " + vnTime); System.out.println("OffSet VN: " + vnTime.getOffset()); } }
Output
Instant : 2022-06-04T12:56:01.538799Z
ZonedDateTime JP: 2022-06-04T21:56:01.538799+09:00[Asia/Tokyo]
OffSet JP: +09:00
ZonedDateTime VN: 2022-06-04T19:56:01.538799+07:00[Asia/Ho_Chi_Minh]
OffSet VN: +07:00
2. ZonedDateTime -> Instant
Convert the Japan ZonedDateTime
UTC+9 back to a Instant
UTC+0/Z, review the result, the offset is taken care automatically.
InstantZonedDateTime2.java
package com.favtuts.time; import java.time.*; public class InstantToZonedDateTime { public static void main(String[] args) { convertZonedDateTimeToInstant(); } static void convertZonedDateTimeToInstant() { LocalDateTime dateTime = LocalDateTime.of(2016, Month.AUGUST, 18, 6, 57, 38); // UTC+9 ZonedDateTime jpTime = dateTime.atZone(ZoneId.of("Asia/Tokyo")); System.out.println("ZonedDateTime : " + jpTime); // Convert to instant UTC+0/Z , java.time helps to reduce 9 hours Instant instant = jpTime.toInstant(); System.out.println("Instant : " + instant); } }
Output
ZonedDateTime : 2016-08-18T06:57:38+09:00[Asia/Tokyo]
Instant : 2016-08-17T21:57:38Z
Download Source Code
$ git clone https://github.com/favtuts/java-core-tutorials-examples
$ cd java-basic/time