Figuring out Date Time Zones in Adobe Flex/Actionscript

I was really frustrated the past few weeks when a major clock component of an app kept failing when viewed from different time zones. It was always supposed to show Antarctica time and only that. I searched and searched for definitive examples on the web, but never found what I needed.

At the heart of this is the ActionScript Date Class. It’s unfortunately a very poor implementation. I expected to simply have a property where you give the Class a timezone offset and presto you magically get the time for that location of the world. Silly me. In addition the documentation is incorrect in that the getTime() method does NOT in fact report the time in UTC. And, to make things even more fun, the getTimeZoneOffset() method returns minutes rather than milliseconds.

However, after enough iterations I was finally able to cobble together what seems to be a graceful solution. The trick is to use the getTime() method. Then add the time zone offset in milliseconds. This, in theory, gives you UTC time. Then add or subtract the number of hours in milliseconds for your fixed clock. Oh, and I also used the DateTimeFormatter to beautify everything up. Here’s the code to hopefully save someone else a bunch of additional coding:

var df:DateTimeFormatter = new DateTimeFormatter();
df.useUTC = false;
df.timeStyle = "short";
df.dateStyle = "medium";
var d:Date = new Date();

var millisecondsPerThreeHours:int = 1000 * 60 * 60 * 3; //using a -3 hour UTC offset
var timeZoneOffsetMilliSeconds:Number = d.getTimezoneOffset() * 60 * 1000;

d.setTime(d.getTime() + timeZoneOffsetMilliSeconds - millisecondsPerThreeHours);

var antarcticaTime2:String = d.toString();
antarcticaTimeTextArea.text = df.format(antarcticaTime2);