java.time.format.DateTimeParseException for dd-MMM

2020-04-04 02:47发布

问题:

I am trying to parse date of dd-MMM-yyyy format.

package com.company;

import javax.swing.text.DateFormatter;
import java.time.format.DateTimeFormatter;

import java.time.*;
import java.util.Locale;

public class Main {

    public static void main(String[] args) {
        // write your code here
        MonthDay m;
        Locale.setDefault(Locale.ENGLISH);
        DateTimeFormatter dTF = DateTimeFormatter.ofPattern("dd-MMM-yyyy");
        String dateString = "12-jan-1900";

        try
        {
            LocalDate ddd = LocalDate.parse(dateString,dTF);
            System.out.println(ddd.toString());
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        //System.out.println(d.toString());

    }
}

It throws the following exception

java.time.format.DateTimeParseException: Text '12-jan-1900' could not be parsed at index 3
    at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
    at java.time.LocalDate.parse(LocalDate.java:400)
    at com.company.Main.main(Main.java:20)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

It parses fine for dd-MM-yyyy format but fails with dd-MMM-yyyy format. I tired setting Locale.US also, but it failed in that case too.

回答1:

The reason is that parsing is case sensitive by default and the formatter doesn't recognize "jan". It would only recognize "Jan".

You can construct a case-insensitive parser by using a DateTimeFormatterBuilder and calling parseCaseInsensitive():

Changes the parse style to be case insensitive for the remainder of the formatter.

Parsing can be case sensitive or insensitive - by default it is case sensitive. This method allows the case sensitivity setting of parsing to be changed.

DateTimeFormatter dTF = 
    new DateTimeFormatterBuilder().parseCaseInsensitive()
                                  .appendPattern("dd-MMM-yyyy")
                                  .toFormatter();