Parse clock time in java 8

安稳与你 提交于 2019-12-29 08:09:12

问题


I wonder is it possible to parse clock time hour:minute:second in Java 8?

e.g.

final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
final String str = "12:22:10";
final LocalDateTime dateTime = LocalDateTime.parse(str, formatter);

I tried but get this exception:

Exception in thread "main" java.time.format.DateTimeParseException: Text '12:22:10' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 12:22:10 of type java.time.format.Parsed

回答1:


Since you only have a time use the LocalTime class:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
String str = "12:22:10";
LocalTime time = LocalTime.parse(str, formatter);

See Oracle Tutorial for more info.



来源:https://stackoverflow.com/questions/39870160/parse-clock-time-in-java-8

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