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

Viewed 82

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:

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?

1 Answers

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
Related