Given an object of Instant
, a time string
representing the time at a specific ZoneId
, How to construct a ZonedDateTime
object with the date part (year, month, day) from the instant at the given ZoneId
and the time part from the given time string
?
For example:
Given an object of Instant of value 1437404400000 (equivalent to 20-07-2015 15:00 UTC), a time string 21:00, and an object of ZoneId
representing Europe/London, I want to construct an object of ZonedDateTime
equivalent to 20-07-2015 21:00 Europe/London.
Conversion Instant instant = Instant. now(); Now we will call the atZone() method on the instant object to convert it to a ZonedDateTime object. ZonedDateTime zonedDateTime = instant.
1.1 Convert Instant to LocalDate via LocalDateTime : First step is to convert Instant to LocalDateTime using LocalDateTime. ofInstant() method passing instant & ZoneOffset. After converting to LocalDateTime, use/invoke toLocalDate() method of LocalDateTime to convert into LocalDate as shown in the below illustration.
ZonedDateTime is an immutable representation of a date-time with a time-zone. This class stores all date and time fields, to a precision of nanoseconds, and a time-zone, with a zone offset used to handle ambiguous local date-times. For example, the value "2nd October 2007 at 13:45.30.
You'll want to parse the time string to a LocalTime
first, then you can adjust a ZonedDateTime
from the Instant
with the zone, and then apply the time. For example:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm", Locale.US);
LocalTime time = LocalTime.parse(timeText, formatter);
ZonedDateTime zoned = instant.atZone(zoneId)
.with(time);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With