Line coverage in LocalTime with / without nanoOfSeconds

I need to convert a string to LocalTime (java-8 not joda), which may or may not have nanoOfSeconds in the string. The format of the String is in the form 07:06:05 or 07:06:05.123456 The string may or may not have a decimal place in seconds, and when possible, there can be any number of characters to represent the Nano Seconds part.

Using DateTimeForamtter e.g.

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

or

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

I can use the IF statement to distinguish between two formats, such as:

 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 fine with that, but I need to also use a variable number of positions after the decimal point.

An example dataset might be:

 [11:07:59.68750, 11:08:00.781250, 11:08:00.773437500, 11:08:01] 

Is there a way to allow formatting parsing any number of digits after the decimal without throwing java.time.format.DateTimeParseException when the number of decimal places is unknown?

I hope that I miss something very simple.

+6
source share
2 answers

There is no need to do anything special to parse this format. LocalTime.parse(String) already processing additional 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 of the parsing described above, see also Javadoc spec .

+16
source

To do this, you can use the "additional sections" of the format template:

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

Source: https://habr.com/ru/post/988944/


All Articles