'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 1:[1]

Create the instant and determine the date in UTC of that instant:

Instant instant = Instant.ofEpochMilli(1437404400000L);
LocalDate date = instant.atZone(ZoneOffset.UTC).toLocalDate();

// or if you want the date in the time zone at that instant:

ZoneId tz = ZoneId.of("Europe/London");
LocalDate date = instant.atZone(tz).toLocalDate();

Parse the time:

LocalTime time = LocalTime.parse("21:00");

Create a ZoneDateTime from the LocalDate and the LocalTime at the desired ZoneId:

ZonedDateTime zdt = ZonedDateTime.of(date, time, tz);

As pointed out by Jon you need to decide which date you want as the date in UTC may be different from the date in the given time zone at that instant.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1