Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 312
YAM Avatar asked Jul 23 '15 16:07

YAM


People also ask

How do I convert instant to ZonedDateTime?

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.

How do I convert instant to LocalDate?

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.

What is the format of ZonedDateTime?

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.


1 Answers

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);
like image 107
Jon Skeet Avatar answered Nov 14 '22 22:11

Jon Skeet