Fun With Java dates

Sorry for not posting anything other than links recently, the kid is wearing me out almost as much as working with Java dates. I haven’t had to work with java.util.Date and java.util.Calendar all that much, most of the time it’s been pretty simple stuff but for whatever reason this past week has been spent waist deep in the Calendar and Date API’s trying to fix a bug in a deployed application. The code I was using looked something like this:

// date entered by user through a combination
// of drop down lists
String strdate = "12/6/1975 5:30 PM"
SimpleDateFormat formatter = new SimpleDateFormat("M/d/yyyy H:m a");
Date eventdate = formatter.parse(strdate);
System.out.println(formatter.format(eventdate));

and out of that I expected to see a date of 12/6/1975 at 5:30pm, it should in fact have printed back the exact same string I entered right? Instead I got:

12/6/1975 5:30 AM

I spent awhile trying different things (am I entering the date wrong? is there something wrong with the timezone? etc..) but eventually noticed that ‘h’ is not the same thing as ‘H’ in the date format string. Using an upper case ‘H’ signifies to the SimpleDateFormat parser that you want it to look for a 24 hour time format (ie: instead of 5:30 I should have used 17:30). In hindsight that’s somewhat obvious, but the tricky thing is that I included the PM designation, so in theory, shouldn’t the SimpleDateFormat have picked up the fact that I wanted a time in PM? I think it should have at least have thrown an exception that says you’ve entered a time in the morning and an AM PM designation of evening. True Date class experts would say at this point that I should have set the SimpleDateFormat to be strict in it’s parsing:

formatter.setLenient(true)

which I did, but it still didn’t throw an exception. Should it have?

One thought on “Fun With Java dates”

Leave a Reply

Your email address will not be published. Required fields are marked *