23/12/2013 is mapping with MM/dd/yyyy format why, why not ParseException

后端 未结 5 551
野性不改
野性不改 2021-01-28 10:20

Can anybody help?

public void dateCalender() throws ParseException{
        System.out.println(new SimpleDateFormat(\"MM/dd/yyyy\", Locale.ENGLISH).parse(\"120/1         


        
相关标签:
5条回答
  • 2021-01-28 10:44

    On the first two:

    MM/dd/yyyy 120/12/2013
    

    The compiler will take this as '12/12/2013 + 118 months' and essentially solve for the correct date. In your example, it comes out as December 12, 2022 (12/12/2013 + 9 years).

    MM/dd/yyyy 23/12/2013
    

    The exact same thing happens. You get '12/12/2013 + 9 months', or 11/12/2014.

    The third one isn't technically in the MM/dd/yyyy format. As from the other answers, you can do something like this:

    SystemDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH);
    sdf.setLenient(true);
    sdf.parse("Jan/12/2013");
    System.out.println(sdf.toString());
    
    0 讨论(0)
  • 2021-01-28 10:47

    You are using the format MM/dd/yyyy .So its taking Two positions

    U try this way:

    System.out.println(new SimpleDateFormat("MMM/dd/yyyy", Locale.ENGLISH).parse("Jan/12/2013").toString());

    Here not throws unparsable exception but am not shoore about that is working or not

    I think this will be wrong way every time using only MM/dd/yyyy format as "1/12/2013"

    0 讨论(0)
  • 2021-01-28 10:51

    According to docs , parsing is lenient, So you didn't get exception for invalid input. It converted to another value.

    By default, parsing is lenient: If the input is not in the form used by this object's format method but can still be parsed as a date, then the parse succeeds. Clients may insist on strict adherence to the format by calling setLenient(false).


    If you want to get java.text.ParseException: Unparseable date:, than apply setLenient(false); at SimpleDateFormat

        String dateStr="120/12/2013";
        SimpleDateFormat sdf=new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH);
        sdf.setLenient(false);
        try {
            Date d=sdf.parse(dateStr);
        } catch (ParseException ex) {
            ex.printStackTrace();
        }
    
    0 讨论(0)
  • 2021-01-28 10:52

    You have to invoke setLenient with false - otherwise SimpleDateFormat will try to "figure out" what month that is. So, first create SimpleDateFormat and invoke sdf.setLenient(false). Now when parsing, you will get exception.

    0 讨论(0)
  • 2021-01-28 10:55

    From the documentation:

    public void setLenient(boolean lenient)
    

    You need to set the format to be non-lenient.

    0 讨论(0)
提交回复
热议问题