I am trying to create a LocalDateTime object from a string that is coming from another system (i.e. I don't have the ability to control it). The LocalDateTime.parse(String, DateTimeFormatter)
method of Java 8 is not correctly able to parse my string. An example of the date string would be 20190813074127111
and the pattern I am using is yyyyMMddHHmmssSSS
. The error is that Text '20190813074127111' could not be parsed at index 0
I have validated my letters in my DateTimeFormatter pattern are correct using the documentation for the letters. I have seen many questions and answers on Stack Overflow very similar to this but none have exactly solved my issue.
I thought that this Stack Overflow was similar to what I am experiencing, which says that the entire String could be being evaluated as a year as I am using yyyy in my pattern string. I tried modifying the pattern to both yyMMddHHmmssSSS
and uuMMddHHmmssSSS
; in both cases the exception changes to Text '20190813074127111' could not be parsed at index 15
I have tried trimming the SSS at the end of my pattern and removing the milliseconds from the input string and that correctly creates a LocalDateTime with the correct date and time, but I don't have the precision provided with the milliseconds, and this use case should be as precise as possible.
I had to remove some details since I am doing this for a company, but this is identical to the use case I am trying to accomplish
public class MyClass {
private static final DateTimeFormatter DATETIME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
public LocalDateTime parseStringToDate(String input) {
return LocalDateTime.parse(input, DATETIME_FORMATTER);
}
}