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

How do I parse a date in September

I am trying to parse dates with the format "27-Sep-2017".

So I tried

String dateStr = "27-Sep-2017";
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd-MMM-uuuu");
fmt.withLocale(Locale.US);
LocalDate d = LocalDate.parse(dateStr, fmt);

but it throws an exception: DateTimeParseException "Text '27-Sep-2017' could not be parsed at index 3".

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

It seems to expect Sept not Sep.
I had assumed that MMM meant a 3-letter date, which seems to work for the other 11 months.

Is there a format pattern that works for Sep too?

>Solution :

fmt.withLocale(Locale.US); doesn’t set the local date on fmt. Instead, it returns a new DateTimeFormatter with that locale. You can either set the locale directly from the ofPattern method:

DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd-MMM-yyyy", Locale.US);

Or, dirtier

String dateStr = "27-Sep-2017";
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd-MMM-uuuu");
fmt = fmt.withLocale(Locale.US); // NOTICE HERE: reassigning fmt
LocalDate d = LocalDate.parse(dateStr, fmt);
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