java.time.format.DateTimeParseException: Text could not be parsed at index 3

Viewed 203571

I am using Java 8 to parse the the date and find difference between two dates.

Here is my snippet:

String date1 ="01-JAN-2017";
String date2 = "02-FEB-2017";

DateTimeFormatter df = DateTimeFormatter .ofPattern("DD-MMM-YYYY", en);
LocalDate  d1 = LocalDate.parse(date1, df);
LocalDate  d2 = LocalDate.parse(date2, df);

Long datediff = ChronoUnit.DAYS.between(d1,d2);

When I run I get the error:

java.time.format.DateTimeParseException: Text could not be parsed at index 3

6 Answers
// DateTimeFormatterBuilder provides custom way to create a
    // formatter
    // It is Case Insensitive, Nov , nov and NOV will be treated same
    DateTimeFormatter f = new DateTimeFormatterBuilder().parseCaseInsensitive()
            .append(DateTimeFormatter.ofPattern("yyyy-MMM-dd")).toFormatter();
    try {
        LocalDate datetime = LocalDate.parse("2019-DeC-22", f);
        System.out.println(datetime); // 2019-12-22
    } catch (DateTimeParseException e) {
        // Exception handling message/mechanism/logging as per company standard
    }

Maybe Someone is looking for this it will work with date Format like 3/24/2022 or 11/24/2022

DateTimeFormatter.ofPattern("M/dd/yyyy")

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M/dd/yyyy");
       formatter = formatter.withLocale( Locale.US );  // Locale specifies human language for translating, and cultural norms for lowercase/uppercase and abbreviations and such. Example: Locale.US or Locale.CANADA_FRENCH
        LocalDate date = LocalDate.parse("3/24/2022", formatter);
        System.out.println(date);

Try using DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-LLL-yyyy",Locale.ENGLISH);

Maybe you can use this wildcard,

 String d2arr[] = {
            "2016-12-21",
            "1/17/2016",
            "1/3/2016",
            "11/23/2016",
            "OCT 20 2016",
            "Oct 22 2016",
            "Oct 23", // default year is 2016
            "OCT 24",  // default year is 2016
    };

    DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder()
            .parseCaseInsensitive().parseLenient()
            .parseDefaulting(ChronoField.YEAR_OF_ERA, 2016L)
            .appendPattern("[yyyy-MM-dd]")
            .appendPattern("[M/dd/yyyy]")
            .appendPattern("[M/d/yyyy]")
            .appendPattern("[MM/dd/yyyy]")
            .appendPattern("[MMM dd yyyy]");

    DateTimeFormatter formatter2 = builder.toFormatter(Locale.ENGLISH);

https://coderanch.com/t/677142/java/DateTimeParseException-Text-parsed-unparsed-textenter link description here

Related