Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java LocalTime Parse Exception

Tags:

java

localtime

I had a piece of code that worked just fine and now somehow doesn't work.

I am reading in a csv file and get an error when reading in a time field of the format 4:38.

My code that throws the exception is:

LocalTime.parse("4:38", DateTimeFormatter.ofPattern("HH:mm"))

I also tried "H:mm" or "H:m" for the pattern but it throws the same exception: Text '4:38' could not be parsed at index 0. Any idea to why it throws an exception at the hour number?

I am using Java 8.

like image 749
k88 Avatar asked Aug 19 '16 08:08

k88


People also ask

How to parse LocalTime in Java?

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

What is LocalTime in Java?

LocalTime is an immutable date-time object that represents a time, often viewed as hour-minute-second. Time is represented to nanosecond precision. For example, the value "13:45.30. 123456789" can be stored in a LocalTime . This class does not store or represent a date or time-zone.

What package is the LocalTime class in Java?

time is a package used to work with the current date and time API. Import classes such as java. time. LocalTime.


1 Answers

The pattern needs one single "H" and one single "m".

LocalTime.parse("4:38", DateTimeFormatter.ofPattern("H:m"));

It works fine for 4:38 and 14:38.

Official Doc: See "Patterns for Formatting and Parsing"

like image 142
debus Avatar answered Oct 02 '22 11:10

debus