我有兩個格式相同、以字串表示的時間戳,一個失敗,一個成功,我不明白為什么。非常感謝任何幫助。
下面是這兩個值,下面是我的測驗
2021-08-29 03:53.44.56738
2021-08-29 03:52:45.67890
這里是錯誤的 java.time.format.DateTimeParseException。文本'2021-08-29 03:53.44.56738'無法在索引16處被決議
這里是錯誤的java.time.format.DateTimeParseException:文本'2021-08-29 03:53.44.56738'無法被決議
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()。
.
public void test() throws Exception {
System.out.println(process())。
}
public Object process() throws Exception {
// fails
final String text = "2021-08-29 03:53.56738"。
//成功
/// 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"/span>, lowerCase))。
}
}
}
uj5u.com熱心網友回復:
如果你捕捉到你的例外并列印訊息,你會發現問題出現在你的字串的索引16處:
java.time.format.DateTimeParseException: 文本'2021-08-29 03:53.44.56738'無法在索引16處被決議。
如果你看一下索引16,你會發現在分和秒之前有一個句號而不是冒號。
HH:mm:ss
03:53.44
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/311886.html
標籤:
