Bet You Are Not Using SimpleDateFormat Correctly
We have all used SimpleDateFormat for some time. I think it’s the most prevalent built-in Java package for parsing and formatting dates and times. Surprise – you may not be using it correctly!
Let’s take a simple example: “MM/dd/yyyy” – a standard US format date string. You would expect that parsing a date string like 2/31/2011 to throw a ParseException error due to the invalid date. Wrong!
A little known attribute of SimpleDateFormat is called lenient. The lenient attribute is defaulted to true. (I am sure there is some theoretical reason for default true) Lenient true means the package will attempt to convert/parse whatever you throw at it and take a guess if the string/date doesn’t quite fit the format passed. So, a date like 2/31 or 29/4 (transpose months and days) produces some date when parsed.
Setting lenient false does what you expect – both dates fail on parse.
Isn’t it fun thinking back about all that code you have written over the years that may not be doing the right thing?

Comments
Leave a comment Trackback