Coverting String to LocalTime with/without nanoOfSeconds

巧了我就是萌 提交于 2019-12-05 00:55:17

There is no need to do anything special to parse this format. LocalTime.parse(String) already handles optional nanoseconds:

System.out.println(LocalTime.parse("10:15:30"));
System.out.println(LocalTime.parse("10:15:30."));
System.out.println(LocalTime.parse("10:15:30.1"));
System.out.println(LocalTime.parse("10:15:30.12"));
System.out.println(LocalTime.parse("10:15:30.123456789"));

All the above parse fine, see also the Javadoc spec.

You could use "optional sections" of the format pattern for this:

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("H:mm:ss[.SSSSSS]");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!