Why Does Java's SimpleDateFormat parse this

后端 未结 3 1173
予麋鹿
予麋鹿 2021-01-11 15:36

Hi I\'ve got a simple date format set up with a custom format string: MMddyy

and I give it the following value to parse: 4 1 01

I don\'t think it should pars

3条回答
  •  耶瑟儿~
    2021-01-11 16:16

    This is expected behaviour - you are telling the DateFormat object to expect a 6 character String representation of a date and that is what you passed in. Spaces are parsed OK. However, if you used "4x1x01" you would get an error. Note that when parsing, leniency defaults to true e.g.

    DateFormat df = new SimpleDateFormat("MMddyy");
    Date date = df.parse("4 1 01"); // runs successfully (as you know)
    
    DateFormat df = new SimpleDateFormat("MMddyy");
    Date date = df.parse("41 01"); // 5 character String - runs successfully
    
    DateFormat df = new SimpleDateFormat("MMddyy");
    df.setLenient(false);
    Date date = df.parse("41 01"); // 5 character String - causes exception
    
    DateFormat df = new SimpleDateFormat("MMddyy");
    Date date = df.parse("999999"); // 6 character String - runs successfully
    
    DateFormat df = new SimpleDateFormat("MMddyy");
    df.setLenient(false);
    Date date = df.parse("999999"); // 6 character String - causes exception
    

    When leniency is set to true (the default behaviour), the parse makes an effort to decipher invalid input e.g. the 35th day of a 31 day month becomes the 4th day of the next month.

提交回复
热议问题