A bit of code that’s been in production for almost a year now came into question recently and I had an opportunity to examine more closely. It was very simple code to get the GMT time and use it to generate an authorization code. The problem was that the GMT time generated on the server and the GMT time generated on the client did not match.

Yes, I too was baffled. How could this make sense? Time calculated for a specific time zone should be the same when calculated simultaneously from two points, regardless of where those points may be. For a moment I thought I’d discovered a rent in the very fabric of time, which might possibly lead to spectacular adventures in history-hopping (and maybe even next year’s stock market status – I could make billions! [but who needs them when you can buy food and eat it, then go back in time so you never bought it?]).

It turns out not all GMT is created equal, at least according to Java’s java.util.Calendar object. A seemingly-simple method for creating a Calendar with the GMT time zone in fact results in the current time zone being used instead!

Calendar calendar = Calendar.getInstance();
// We want only the current year, month, day, and hour;
// Use GMT so it's standard across all time zones
calendar.set(Calendar.ZONE_OFFSET, 0);
calendar.setTimeZone(TimeZone.getTimeZone("GMT"));

Using this code while your computer’s clock is set to CST will result in a CST Calendar being generated! Instead the following snippet can be used to get an actual GMT Calendar object:

Calendar calendar = Calendar.getInstance(new SimpleTimeZone(0, "GMT"));

It seems that passing the expected time zone in as a constructor argument is much more accurate than using the setter methods after the object has already been created.