I am receiving instant from a service and below are the cases.
In first case, say instant = "2021-03-23T04:17:35Z" & In second case,
instant = "2021-07-15T05:27:00Z"
Then required to convert instant to offsetDateTime, doing like
OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.UTC)
Now I want to calculate hours gap between above offsetDateTime and instant.now
ChronoUnit.HOURS.between(Instant.parse(offsetDateTime), Instant.now())
Results
case 1 : it works fine
case 2 : ERROR :
DateTimeParseException: Text '2021-07-15T05:27Z' could not be parsed at index 16
Figured out the reason :
in case 2, if it would have pass the same 2021-07-15T05:27:00Z. it would work but as instant.atOffset(ZoneOffset.UTC) internally will call to below method, where zero would be removed, basically minute part will be sorted out. so below fn will return 2021-07-15T05:27Z , this will lead to DateTimeParseException.
public static OffsetDateTime ofInstant(Instant instant, ZoneId zone) {
Objects.requireNonNull(instant, "instant");
Objects.requireNonNull(zone, "zone");
ZoneRules rules = zone.getRules();
ZoneOffset offset = rules.getOffset(instant);
LocalDateTime ldt = LocalDateTime.ofEpochSecond(instant.getEpochSecond(), instant.getNano(), offset);
return new OffsetDateTime(ldt, offset);
}
One solution I am assuming manually append the zero but that's might not be good practice.