A developer is writing a method that takes a LocalDate and a ZoneId and returns the current time in that time zone as an OffsetDateTime. Which approach correctly implements this?
Trap 1: OffsetDateTime.of(LocalDateTime.now(),…
Complicated and incorrect; ZoneOffset.from() may throw DateTimeException.
Trap 2: LocalDate.now(zone).atStartOfDay(zone).toOffsetDateTime()
atStartOfDay() returns start of day, not current time.
Trap 3: LocalDateTime.now().atZone(zone).toOffsetDateTime()
LocalDateTime.now() uses system default zone, not the given zone.
- A
OffsetDateTime.of(LocalDateTime.now(), ZoneOffset.from(ZonedDateTime.now(zone)))
Why wrong: Complicated and incorrect; ZoneOffset.from() may throw DateTimeException.
- B
ZonedDateTime.now(zone).toOffsetDateTime()
Gets current instant in given zone and converts to OffsetDateTime.
- C
LocalDate.now(zone).atStartOfDay(zone).toOffsetDateTime()
Why wrong: atStartOfDay() returns start of day, not current time.
- D
LocalDateTime.now().atZone(zone).toOffsetDateTime()
Why wrong: LocalDateTime.now() uses system default zone, not the given zone.