I am using Java 8. I am trying to parse a date to string with DateTimeFormatter. But it gives the following error. My attempt and error are given below.
My code:
String getFormatedDateForList(String dateObj) { // dateObj = "2019-02-06 00:00:00.0" DateTimeFormatter inputFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); DateTimeFormatter outputFormat = DateTimeFormatter.ofPattern("dd/MM/yyyy"); String output = LocalDate.parse(dateObj, inputFormat).format(outputFormat) return output }
Error:
Text '2019-02-06 00:00:00.0' could not be parsed, unparsed text found at index 19. Stacktrace follows: Message: Text '2019-02-06 00:00:00.0' could not be parsed, unparsed text found at index 19
Advertisement
Answer
Your input formatting pattern yyyy-MM-dd HH:mm:ss
specifies the first 19 characters, while your input dateObj
contains more than that. Hence the parser finds unparsed text from the 20th character (index 19) onwards.
Given you have a tenth of a second in dateObj
, you need to specify that in your formatting pattern. Based on the API, I think you want:
yyyy-MM-dd HH:mm:ss.S