[英]Coverting String to LocalTime with/without nanoOfSeconds
I need to convert a string to LocalTime (java-8 not joda) that may or maynot have nanoOfSeconds in the string. 我需要将一个字符串转换为LocalTime(java-8而不是joda),该字符串可能有也可能没有nanoOfSeconds。 The String format is in the form of 07:06:05
or 07:06:05.123456
The string may or may not have a decimal place in the seconds and when it does there could be any number of characters to represent the Nano Seconds part. 字符串格式的形式为07:06:05
或07:06:05.123456
字符串在秒内可能有或没有小数位,当它出现时,可能有任意数量的字符来表示Nano Seconds部分。
Using a DateTimeForamtter such as 使用DateTimeForamtter等
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("H:mm:ss");
or 要么
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("H:mm:ss.SSSSSS");
I can use an IF statement to distinguish between the two formats such as: 我可以使用IF语句来区分两种格式,例如:
DateTimeFormatter dtf;
if (time1.contains(".") {
dtf = DateTimeFormatter.ofPattern("H:mm:ss.SSSSSS);
} else {
dtf = DateTimeFormatter.ofPattern("H:mm:ss);
}
This works fine and I'm OK with this but I need to be able to also use a varying number of positions after the decimal point. 这工作正常,我很好,但我需要能够在小数点后使用不同数量的位置。
A sample data set might be: 示例数据集可能是:
[11:07:59.68750, 11:08:00.781250, 11:08:00.773437500, 11:08:01]
Is there a way to allow the formatter to parse any number of digits after the decimal without it throwing a java.time.format.DateTimeParseException
when the number of decimal places is unknown? 有没有办法允许格式化程序解析小数点后的任意位数而不会在小数位数java.time.format.DateTimeParseException
时抛出java.time.format.DateTimeParseException
?
I'm hoping I missing something really simple. 我希望我遗漏一些非常简单的东西。
There is no need to do anything special to parse this format. 没有必要做任何特殊的事情来解析这种格式。 LocalTime.parse(String)
already handles optional nanoseconds: LocalTime.parse(String)
已处理可选的纳秒:
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 . 以上所有解析都很好,另见Javadoc 规范 。
您可以使用格式模式的“可选部分”:
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("H:mm:ss[.SSSSSS]");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.