Converting between Instant and LocalDateTime, ZonedDateTime, and OffsetDateTime

These common conversions can be accomplished as in the following examples:

  • Convert between Instant and LocalDateTime—since LocalDateTime has no idea of time zone, use a zero offset UTC+0:
// 2019-02-24T15:27:13.990103700
LocalDateTime ldt = LocalDateTime.ofInstant(
Instant.now(), ZoneOffset.UTC);

// 2019-02-24T17:27:14.013105Z
Instant instantLDT = LocalDateTime.now().toInstant(ZoneOffset.UTC);
  • Convert between Instant and ZonedDateTime—convert an Instant UTC+0 to a Paris ZonedDateTime UTC+1:
// 2019-02-24T16:34:36.138393100+01:00[Europe/Paris]
ZonedDateTime zdt = Instant.now().atZone(ZoneId.of("Europe/Paris"));

// 2019-02-24T16:34:36.150393800Z
Instant instantZDT = LocalDateTime.now()
.atZone(ZoneId.of("Europe/Paris")).toInstant();
  • Convert between Instant and OffsetDateTime—specify an offset of 2 hours:
// 2019-02-24T17:34:36.151393900+02:00
OffsetDateTime odt = Instant.now().atOffset(ZoneOffset.of("+02:00"));

// 2019-02-24T15:34:36.153394Z
Instant instantODT = LocalDateTime.now()
.atOffset(ZoneOffset.of("+02:00")).toInstant();

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.122.127