Search code examples
javajava-8java-timezoneddatetime

How to construct ZonedDateTime from an Instant and a time string?


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.


Solution

  • 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);