How to parse time in any format with LocalTime.parse?

时光毁灭记忆、已成空白 提交于 2020-05-15 10:09:13

问题


I am having trouble using java's LocalTime to parse a string with hours, minutes, and seconds.

LocalTime t = LocalTime.parse("8:30:17"); // Simplification

This throws the following exception:

Exception in thread "main" java.time.format.DateTimeParseException: Text '8:30:17' could not be parsed at index 0


回答1:


You'll need to pass in a custom DateTimeFormatter like this:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("H:mm:ss");
LocalTime t = LocalTime.parse(times.get(i), formatter);

Take a look at the docs, as the letters you need to use might be different.




回答2:


The default formatter expects an ISO format, which uses 2 digits for each of the hours, minutes and seconds.

If you want to parse the time you showed, which only has one digit for hours, you will need to provide a custom formatter (note the single H):

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("H:mm:ss");
LocalTime t = LocalTime.parse(times.get(i), formatter);



回答3:


You need to use DateTimeFormatter to give parser a format pattern to parse.

DateTimeFormatter formatter =DateTimeFormatter.ofPattern("H:mm:ss");
LocalTime t = LocalTime.parse(times.get(i), formatter);

Format Pattern Letters:

H       hour-of-day (0-23)
m       minute-of-hour
s       second-of-minute            
h       clock-hour-of-am-pm (1-12)



回答4:


From LocalTime.parse:

The string must represent a valid time and is parsed using DateTimeFormatter.ISO_LOCAL_TIME.

According to ISO_LOCAL_TIME the condition for the hours is this:

Two digits for the hour-of-day. This is pre-padded by zero to ensure two digits.

You are parsing the value 8:30:17, one digit instead of two digits and so you are breaking the condition, causing the error.



来源:https://stackoverflow.com/questions/61159012/how-to-parse-time-in-any-format-with-localtime-parse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!