I have two timestamps represented as Strings in the same format, one fails and one succeeds, and I can't understand why. Any help is greatly appreciated.
Here are the two values and below my test
2021-08-29 03:53.44.56738
2021-08-29 03:52:45.67890
Here's the error 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));
}
}
}
CodePudding user response:
If you catch your exception and print the message, you'll see that the problem is at index 16 of your string:
java.time.format.DateTimeParseException: Text '2021-08-29 03:53.44.56738' could not be parsed at index 16
If you look at index 16, you'll see there is a period instead of a colon after the minutes and before the seconds.
HH:mm:ss
03:53.44