java-8date-conversionlocaldatetimeoffsetdatetime

How to convert LocalDateTime to OffsetDateTime?


How to convert LocalDateTime to OffsetDateTime?

private OffsetDateTime getEntryDate(Payment payment) {
    return Optional.ofNullable(payment)
                   .map(Payment::getEntryDate)
                   .map(SHOULD RETURN OffsetDateTime)
                   .orElse(null);
}

Payment::getEntryDate will return LocalDateTime


Solution

  • You need to obtain the ZoneOffset to use when creating your OffsetDateTime. One approach is to use a ZoneId for your location:

    final ZoneId zone = ZoneId.of("Europe/Paris");
    LocalDateTime localDateTime = LocalDateTime.now();
    ZoneOffset zoneOffSet = zone.getRules().getOffset(localDateTime);
    OffsetDateTime offsetDateTime = localDateTime.atOffset(zoneOffSet);
    System.out.println(offsetDateTime); // 2019-08-08T09:54:10.761+02:00