Go for OffsetDateTime
You are not using the right types. Your string value, 2021-04-14T20:51:21.527Z
, is appropriate for either an Instant
or an OffsetDateTime
. Your use of LocalDateTime
in particular seems to indicate to me that you need date and/or time of day, not just the moment in time. If so, go for an OffsetDateTime
.
protected final OffsetDateTime dateTimeOfLoss
= OffsetDateTime.parse("2021-04-14T20:51:21.527Z");
Then you should not have any good use for LocalDateTime
nor ZonedDateTime
. If you still need one of those, maybe for an API that you cannot change, write a conversion method:
protected LocalDateTime getDateTimeOfLossLdt() {
return dateTimeOfLoss.toLocalDateTime();
}
protected ZonedDateTime getZdt() {
return dateTimeOfLoss.atZoneSameInstant(dateTimeOfLoss.getOffset());
}
Why?
LocalDateTime
is not right: There are few good uses for LocalDateTime
at all. Most often date and time is used for establishing a point in time, and your string does that by including the trailing Z
that denotes offset zero from UTC. By converting to LocalDateTime
you are discarding that offset and hence losing information about which moment in time you had and getting nothing in return. LocalDateTime
gives you nothing that OffsetDateTime
does not give you.
ZonedDateTime
is not right: As I said, your string contains a UTC offset. It does not contain a time zone. Asia/Krasnoyarsk and America/Grand_Turk are examples of time zones. So while a ZonedDateTime
works, it’s really unmotivated. I think of it as more heavy-weight than you need since a time zone includes historic and known future UTC offsets, information that you cannot meaningfully use here.