Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Using a DateTimeForamtter such as

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:

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?

I'm hoping I missing something really simple.

like image 897
jbolt Avatar asked Jun 11 '15 18:06

jbolt


People also ask

How to parse a String to LocalTime in Java?

parse(CharSequence text)parse() method of a LocalTime class used to get an instance of LocalTime from a string such as '10:15:45′ passed as parameter. The string must have a valid date-time and is parsed using DateTimeFormatter. ISO_LOCAL_TIME.

Is LocalTime immutable?

LocalTime is an immutable date-time object that represents a time, often viewed as hour-minute-second. Time is represented to nanosecond precision.

What is LocalTime format in Java?

LocalTime format() method in Java with ExamplesThe format() method of a LocalTime class is used to format this time using the specified formatter passed as a parameter. This method formats this time based on passed formatter to a string.


2 Answers

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.

like image 124
JodaStephen Avatar answered Oct 08 '22 04:10

JodaStephen


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

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("H:mm:ss[.SSSSSS]");
like image 21
Jon Skeet Avatar answered Oct 08 '22 04:10

Jon Skeet