How to build ZonedDateTime from Instant and time string?
Given an object Instant
, a time string
, representing a time at a particular time ZoneId
, how to build an object ZonedDateTime
with a date part (year, month, day) from a moment at a given ZoneId
time and a time part from a given one time string
?
For example:
For an Instant object of value 1437404400000 (equivalent to 07/20/2015 15:00 UTC ), a time string of 21:00 and an object ZoneId
representing Europe / London , I want to build an object ZonedDateTime
equivalent to 07/20/2015 21:00 Europe / London .
source to share
First you need to parse the time string first LocalTime
, then you can adjust ZonedDateTime
from Instant
using 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);
source to share
Create a moment and define the date in UTC of that moment:
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 ZoneDateTime from LocalDate and LocalTime at the desired ZoneId:
ZonedDateTime zdt = ZonedDateTime.of(date, time, tz);
As John pointed out, you need to decide which date you want as the date in UTC may be different from the date in the given timezone at that moment.
source to share