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

can't convert String to MMM/dd/yyy format in java

I try to convert an input type String into LocalDate with format "MMM/dd/yyyy", but when I enter input, it throws an exception:

Exception in thread "main" java.time.format.DateTimeParseException:
Text ‘DEC/12/1999’ could not be parsed at index 0

Here is my code:

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

Scanner sc = new Scanner(System.in);
DateTimeFormatter format1 = DateTimeFormatter.ofPattern("MMM/dd/yyyy");
System.out.print("Please enter the first date: ");
LocalDate firstDate = LocalDate.parse(sc.nextLine(), format1);
System.out.print("Please enter the second date: ");
System.out.println(firstDate);

How can I fix this?

>Solution :

You have to take care of several things when parsing a String like "DEC/12/1999":

  • abbreviations of months do not have a global standard, they differ in language (e.g. English, French, Japanese…) and style (e.g. trailing dot or not)
  • there’s a difference in parsing lower-case month abbreviations and those in upper-case

That’s why you have to make sure your DateTimeFormatter really knows what to do, I think it won’t do if simply build by .ofPattern(String, Locale).

Give it information about the String to be parsed:

  • make it parse case-insensitively by applying parseCaseInsensitive()
  • make it consider language and style by defining a Locale

You can use a DateTimeFormatterBuilder in order to do that, here’s an example:

public static void main(String[] args) throws IOException {
    // example input
    String date = "DEC/12/1999";
    // Build a formatter, that...
    DateTimeFormatter dtf = new DateTimeFormatterBuilder()
                                // parses independently from case,
                                .parseCaseInsensitive()
                                // parses Strings of the given pattern
                                .appendPattern("MMM/dd/uuuu")
                                // and parses English month abbreviations.
                                .toFormatter(Locale.ENGLISH);
    // Then parse the String with the specific formatter
    LocalDate localDate = LocalDate.parse(date, dtf);
    //and print the result in a different format
    System.out.println(localDate.format(DateTimeFormatter.ISO_LOCAL_DATE));
}

Output:

1999-12-12
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