How do I convert the datetime that is passed as string 2018-08-10T18:25:00.000+0000 to a Instant? I tried the below and it did not work.
public static Instant toInstant(final String timeStr) {
if (StringUtils.isBlank(timeStr)) {
throw new IllegalArgumentException("Invalid date time value passed [" + timeStr + "]");
}
try {
return LocalDate.parse(timeStr).atStartOfDay().toInstant(ZoneOffset.UTC);
} catch (Exception e) {
try {
return LocalDateTime.parse(timeStr).toInstant(ZoneOffset.UTC);
} catch (Exception e1) {
try {
return ZonedDateTime.parse(timeStr).toInstant();
} catch (Exception e2) {
try {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
return LocalDateTime.parse(timeStr, formatter).toInstant(ZoneOffset.UTC);
} catch (Exception e3) {
try {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
return LocalDateTime.parse(timeStr, formatter).toInstant(ZoneOffset.UTC);
} catch (Exception e4) {
try {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSS");
return LocalDateTime.parse(timeStr, formatter).toInstant(ZoneOffset.UTC);
} catch (Exception e5) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
return LocalDateTime.parse(timeStr, formatter).toInstant(ZoneOffset.UTC);
} finally {
throw new IllegalArgumentException("Incorrect date time value passed [" + timeStr + "]");
}
}
}
}
}
}
}
Your trouble is here:
} finally {
throw new IllegalArgumentException("Incorrect date time value passed [" + timeStr + "]");
}
Your parsing is successful in these lines (but may give an incorrect result):
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
return LocalDateTime.parse(timeStr, formatter).toInstant(ZoneOffset.UTC);
After you have successfully parsed your string, in your finally
block you are throwing an exception. So the caller does not receive the result and instead gets an exception and will have to think that parsing or conversion failed.
An incorrect result? Your parsing into LocalDateTime
throws away the UTC offset in the string, +0000
. Next your conversion to Instant
assumes UTC, which in this case happens to agree with the string. If the offset in the string had been anyting else than +0000
(for example, +0100
), you will get an incorrect Instant
.
The other answers show correct ways of converting your string to Instant
.