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
The LocalDateTime has no time zone; to convert the LocalDateTime to ZonedDateTime , we can use . atZone(ZoneId. systemDefault()) to create a ZonedDateTime containing the system default time zone and convert it to another time zone using a predefined zone id or offset.
In Java, with a given LocalDateTime object we can use the LocalDateTime. toEpochSecond(ZoneOffset offset) method to convert it to an epoch seconds value which is the number of seconds from the epoch of 1970-01-01T00:00:00Z as the example Java code below. The output as below.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With