Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Read date as defined localdate from file and throw DateTimeParseException in Java

I have a problem about reading date part from txt and define them as localdate in the object.

Here are example values in txt file.

1-11-2022
11-10-2022
3-12-2022
...

Here is the code snippets shown below.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
...
object.setDate(LocalDate.parse(objectValue[0], formatter));  // HERE IS ERROR
...

Here is the error shown below.

Exception in thread "main" java.time.format.DateTimeParseException: Text '1-11-2022' could not be parsed at index 0

How can I fix it?

>Solution :

As specified in the documentation of DateTimeFormatter, dd indicates that the expected minimum number of digits is two, and you need to have a leading zero in your string (i.e. 1 -> 01 and 3 -> 03) for this formatting pattern to work.

Number:

If the count of letters is one, then the value is output using the
minimum number of digits and without padding. Otherwise, the count of digits is used as the width of the output field, with the value
zero-padded as necessary
.

Instead, you can use pattern "d-MM-yyyy" which would be able to parse both "3-12-2022" and "11-10-2022".

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading