I’ve just found an annoying bug in a product at work. I was formatting a date (as part of a test) and expecting to get back a known value. The easiest way to do this is:
Date when = new Date(0); // 1970-01-01 00:00:00 SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd't'HH:mm:ss"); String whenStr = fmt.format(when);
Sadly, this produced a date which was an hour out.
Thankfully, the fix is simple (when you know how).
Date when = new Date(0); // 1970-01-01 00:00:00 SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd't'HH:mm:ss"); fmt.setTimeZone(TimeZone.getTimeZone("GMT")); String whenStr = fmt.format(when);
It’s usually a good idea to always work in GMT. Or UTC. Or Zulu time.
On a slightly related note, I really hope that JSR 310 gets in to Java 7 (though don’t get me started on the opaqueness of the JSR process). It’s a fresh DateTime api based upon joda time. Anything is better than Date and Calendar, let’s hope it does what DateTime did for Perl.
One reply on “Dates & Time Zones in Java”
+1 on Joda Time – it’s like a breath of fresh air when dealing with date, times, timezones.