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

后端 未结 5 1453
醉酒成梦
醉酒成梦 2021-02-06 23:36

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         


        
5条回答
  •  执念已碎
    2021-02-07 00:28

    First of all, check the javadoc. The uppercase D represents the day-of-year field (not the day-of-month as you want), and uppercase Y represents the week-based-year field (not the year as you want). The correct patterns are the lowercase letters d and y.

    Also, you're using month names in uppercase letters (JAN and FEB), so your formatter must be case insensitive (the default behaviour is to accept only values like Jan and Feb). And these month names are English abbreviations, so you must also use English locale to make sure it parses the names correctly (using java.util.Locale class).

    So, your formatter should be created like this:

    DateTimeFormatter df = new DateTimeFormatterBuilder()
        // case insensitive to parse JAN and FEB
        .parseCaseInsensitive()
        // add pattern
        .appendPattern("dd-MMM-yyyy")
        // create formatter (use English Locale to parse month names)
        .toFormatter(Locale.ENGLISH);
    

    This will make your code work (and datediff will be 32).

提交回复
热议问题