Java 使用/不使用 nanoOfSeconds 将字符串转换为 LocalTime

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30788369/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 10:10:54  来源:igfitidea点击:

Coverting String to LocalTime with/without nanoOfSeconds

javajava-8formatterjava-timelocaltime

提问by jbolt

I need to convert a string to LocalTime (java-8 not joda) that may or maynot have nanoOfSeconds in the string. The String format is in the form of 07:06:05or 07:06:05.123456The 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.

我需要将字符串转换为 LocalTime(java-8 不是 joda),字符串中可能有也可能没有 nanoOfSeconds。字符串格式的形式为 07:06:05or07:06:05.123456字符串在秒中可能有也可能没有小数位,当它出现时,可能有任意数量的字符来表示纳米秒部分。

Using a DateTimeForamtter such as

使用 DateTimeFormatter 如

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.DateTimeParseExceptionwhen the number of decimal places is unknown?

有没有办法允许格式化程序解析小数点后任意数量的数字,而不会java.time.format.DateTimeParseException在小数位数未知时抛出 a ?

I'm hoping I missing something really simple.

我希望我错过了一些非常简单的东西。

采纳答案by JodaStephen

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 Javadocspec.

以上所有解析都很好,另请参阅Javadoc规范

回答by Jon Skeet

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

您可以为此使用格式模式的“可选部分”:

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("H:mm:ss[.SSSSSS]");