DateTimeParseException意外结果



我有两个时间戳,以相同的格式表示为字符串,一个失败,一个成功,我不明白为什么。非常感谢任何帮助。下面是我测试的两个值

下面是错误java.time.format.DateTimeParseException: Text '2021-08-29 03:53.44.56738' could not be parsed at index 16


private static final int START_OF_MONTH = 1;
private final static DateTimeFormatter DEFAULT_TIMESTAMP_FORMATTER = new DateTimeFormatterBuilder()
.appendPattern("yyyy-MM-dd HH:mm:ss")
.appendFraction(ChronoField.MICRO_OF_SECOND, 0, 6, true)// min 0 max 6
.toFormatter();
@Test
public void test() throws Exception {
System.out.println(process());
}
public Object process() throws Exception {
// fails
final String text = "2021-08-29 03:53.44.56738";
// succeeds
// final String text = "2021-08-29 03:52:45.67890";
final String lowerCase = text.toLowerCase();
final TemporalAccessor ta = DEFAULT_TIMESTAMP_FORMATTER.parse(lowerCase);
if (ta.isSupported(ChronoField.HOUR_OF_DAY)) {
return Timestamp.valueOf(LocalDateTime.from(ta));
} else if (ta.isSupported(ChronoField.DAY_OF_MONTH)) {
return Timestamp.valueOf(LocalDate.from(ta).atStartOfDay());
} else if (ta.isSupported(ChronoField.MONTH_OF_YEAR)) {
return Timestamp.valueOf(YearMonth.from(ta).atDay(START_OF_MONTH).atStartOfDay());
} else {
throw new IllegalArgumentException(String.format("[%s] is not a supported date format", lowerCase));
}
}
}

如果捕获异常并打印消息,您将看到问题出现在字符串的索引16处:

java.time.format.DateTimeParseException: Text '2021-08-29 03:53.44.56738' could not be parsed at index 16

如果你看索引16,你会看到在分之后和秒之前有一个句号而不是冒号。

HH:mm:ss

03:53.44

相关内容

  • 没有找到相关文章

最新更新