I was tracking down some unusual date behaviour and came across this little gem. Check out the following code and tell me what the output should be…
DateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z"); Date startDate = new Date(); String strDate = formatter.format(startDate); Date parsedDate = formatter.parse(strDate); System.out.println("Start Date is: [" + startDate +"] Parsed Date is: [" + parsedDate + "]");
Looks pretty straight ahead. Create a new date formatter, apply it to a Date object, output the string, and then reverse the process. Should end up with what you started with. Well, if you try it in Australia on a JDK that’s pre 5.0 you’ll get this:
Start Date is: [Wed Mar 22 **13:53:18** EST 2006] Parsed Date is: [Wed Mar 22 **14:53:18** EST 2006]
Whoa there! Where did that extra hour come from? It all comes back to that magic z in the format string. Seems there are issues with that TimeZone parsing story pre JDK 5.0. Going on the Pragmatic Programmer “select() isn’t broken” philosophy, it took me a long while to assume the problem wasn’t in my code, and finally to check out the bug parade. But sure enough, let me introduce you to bug 4845901.
You have been warned…