Converting Instants – Date and Time

Converting Instants

Each of the classes LocalTime, LocalDate, LocalDateTime, and ZonedDateTime provides the ofInstant() method to obtain a temporal object from an Instant. The code below shows how instants can be converted to other temporal objects for a given time zone. For date/time represented by this particular instant, the offset for the time zone “America/New_York” is -4 hours from UTC.

Click here to view code image

Instant instant = Instant.parse(“2021-04-28T03:15:00Z”);
ZoneId zid = ZoneId.of(“America/New_York”);
LocalTime lt = LocalTime.ofInstant(instant, zid);           // 10:18:30
LocalDate ld = LocalDate.ofInstant(instant, zid);           // 2021-04-27
LocalDateTime ldt = LocalDateTime.ofInstant(instant, zid);  // 2021-04-27T23:15
ZonedDateTime zdt = ZonedDateTime.ofInstant(instant, zid);
    // 2021-04-27T23:15-04:00[America/New_York]

Click here to view code image

static
TemporalType
 ofInstant(Instant instant, ZoneId zone)

Creates a TemporalType object from the given Instant and ZoneId (p. 1072), where TemporalType can be LocalTime, LocalDate, LocalDateTime, or ZonedDateTime.

17.5 Working with Periods

For representing an amount of time, the Date and Time API provides the two classes Period and Duration. We will concentrate on the Period class in this section and discuss the Duration class in ยง17.6, p. 1064.

The Period class essentially represents a date-based amount of time in terms of years, months, and days, whereas, the Duration class represents a time-based amount of time in terms of seconds and nanoseconds.

The date-based Period class can be used with the LocalDate class, and not surprisingly, the time-based Duration class can be used with the LocalTime class. Of course, the LocalDateTime class can use both temporal amount classes.

The Period and Duration classes are in the same package (java.time) as the temporal classes, and the repertoire of methods they provide should look familiar, as they share many of the method prefixes with the temporal classes (Table 17.2, p. 1026).

The mantra of immutable and thread-safe objects also applies to both the Period and the Duration classes.