Skip to content

SimpleDateFormat seems to allow a year of yy when the format is set to dd/mm/yyyy [closed]

If I have this:

private static final String DATE_FORMAT = "dd/MM/yyyy";
DateFormat formatter = new SimpleDateFormat(DATE_FORMAT);

Should my application throw an exception if a 2 digit year is passed in? It doesn’t seem to have any issue with this.


No. SimpleDateFormat is used for both parsing a Date from a String and generating a String from a Date. The interpretation of the format String varies between these usages. In your case, you are parsing a Date from a String. The 98 is a legitimate value and is interpreted literally (i.e. 98 AD) because you are using yyyy. If you replace the yyyy with yy or y then the parsing should interpret the 98 as 1998. If you want require 4-digit dates then you will need to add some verification code to do that.

Note that setLenient doesn’t affect anything here because the values in each position are legitimate. You are not required to have 4 digits in the year position (nor are you limited to 4 digits). If the interpretation is not-lenient and you pass it “1998/04/12” it will throw an exception because 1998 is not in the range of 1-12. If you set lenient then it will mod the value to get it into range (1998 becomes 6) and charge forward. Since the year has no real bounds it has no effect on the year position.