如何将作为字符串 2018-08-10T18:25:00.000+0000 传递的日期时间转换为 Instant?我尝试了以下方法,但没有成功。
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 + "]");
}
}
}
}
}
}
}