Learn to convert a specified Instant (in UTC) to ZonedDateTime (at some zone) with easy-to-follow Java examples.
1. Difference between Instant and ZonedDateTime
An Instant is a point on the UTC timeline without any timezone information associated with it. Generally, a system UTC clock is used to obtain an instant, so its zone offset is zero.
A ZonedDateTime is a point on the timeline with an associated timezone. We get an instance of ZonedDateTime in a specific time zone by adjusting the UTC instant with a zone offset for that time zone.
ZonedDateTime = Instant + Zoneoffset adjustment
2. Convert Instant to ZonedDateTime
There are two simple ways to obtain a zoned datetime instance for a given instant in UTC:
The atZone() method combines the instant with a time-zone (specified by zoneId) to create a ZonedDateTime.
Instant instant = Instant.now(); ZonedDateTime istZdt = instant.atZone(ZoneId.of("Asia/Kolkata"));
2.2. ZonedDateTime.ofInstant(instant, zoneId)
The ofInstant() obtains an instance of ZonedDateTime in the specified timezone from the specified Instant.
Instant instant = Instant.now(); ZonedDateTime istZdt = ZonedDateTime.ofInstant(instant, ZoneOffset.of("+05:30"));
3. From ZonedDateTime to Instant
To convert back from ZonedDateTime to Instant is rather simple. Use the zonedatetime.toInstant() method that returns an Instant representing the same point on the UTC timeline.
ZonedDateTime zdt = ZonedDateTime.now(); Instant instant = zdt.toInstant(); //in UTC
In this short Java date-time tutorial, we learned to convert from Instant to ZonedDateTime and reverse by adjusting the zone offsets.
Happy Learning !!