Friday, August 04, 2006

Programming: Dumb Java Dates Gotcha


Even experienced Java programmers run into time-wasting gotcha's like this one I encountered today. In hindsight, it was almost stupid of me to not have known, but I suppose that's why the saying goes - experience teacheth a fool.

Look at the code in the graphic: very simple and straightforward. The program obtains the current date/time (line 24) and then attempts to set the time component to 1 second before midnight. It calls the function setTimeToBeforeMidnight (line 28), passing it the date/time to modify accordingly.
To reset specific components of a date/time, you have to instatiate a calendar object (line 10), which allows access to individual time components such as the day, month, year, minute, century, millisecond, am/pm marker, etc. In this example, I'm only interested in setting the time to 11:59:59 PM, and thus I only modify the hour, minute, and second components (lines 14-16). Easy, right?

Well, the output at the bottom tells the tale. Somehow I'm in the next day at 11:59:59 AM! What the hell went wrong? This will sound stupid, but a bug I had in one of my programs was caused by this simple, um, assumption. It cost me about 4 hours to find ...
The problem is at line 14! Passing the date into a calendar somehow advances the day and flips the time 12 hours. Come to find out, Calendar.HOUR assumes your want to use 12-hour time, so it does the necessary adjustments for you.

The easy answer: use Calendar.HOUR_OF_DAY. There's such a thing as 12-hour and 24-hour time. Now, if I had read the specification, of course I would have known. But such are the perils of any software development projects ... little things you might overlook can cost you bugs! With this, a huge sigh of relief as a few mysterious bugs in my program are resolved.