Actionscript Date Lunacy

Aug 20
2009

I really hate the Actionscript Date class. Mostly because of the way it deals with local time offsets. When I create a new date instance, I generally don’t care about the local time zone settings. I’ll care about them when I have to combine it with other dates, sure, but at the time I set that value I want it to stay that value. The AS date class thinks otherwise.

Say I have a number of milliseconds from epoch (1 Jan 1970) which I want to use to create a specific date so I can use a DateFormatter to output the result, then you’d think that the following would be fine :

var myDate:Date = new Date(1250766979000);
var df:DateFormatter = new DateFormatter();
df.formatString = "YYYY-MM-DD JJ:NN:SS";
var stringDate:String = df.format(myDate);

(Let’s gloss over the batshit-insane need for a DateFormatter class and the actual formatString itself – JJ for 0-23 hour time, really?)

But no. In my area, we’re currently in daylight savings mode, so the Flash player decides that this date must be modified accordingly, and if you format it with the code above you’ll get “2009-08-20 12:16:19″, whereas it should be “2009-08-20 11:16:19″ (you can try and calculate this yourself if you’re feeling particularly bored). This sounds fairly trivial to deal with until you realise that, short of writing your own DateFormatter, there’s no way to output the actual, formatted UTC date and time (ignoring the unformattable toUTCString() method).

To do that, you have to take this approach :

var myDate:Date = new Date(1250766979000);
myDate.setTime(myDate.getTime() + myDate.timezoneOffset * 60 * 1000);
var df:DateFormatter = new DateFormatter();
df.formatString = "YYYY-MM-DD JJ:NN:SS";
var stringDate:String = df.format(myDate);

Which, to me at least, seems mental, because we haven’t really created a UTC date there – we’ve actually had to modify the milliseconds since epoch due to the local timezone settings. If I change the time settings on my computer, the output of this will still change! It’s possible I’ve lived too long in Microsoft-land, but the equivalent code in C# seems a million times better and far more predictable :

DateTime dat = new DateTime(1970, 1, 1).Add(new TimeSpan(12507669790000000L));
string stringDate = dat.ToString("yyyy-MM-dd HH:mm:ss");

Yes, miraculously, dates can format themselves in C#! There’s no need for a superfluous DateFormatter class. The only reason this code might look a litte overinflated is that dates in C# have a wider range, so I’ve had to convert the milliseconds since Unix epoch to 10’s of nanoseconds since 0001-1-1 00:00:00.

Visit Our Friends!

A few highly recommended friends...

Archives

All entries, chronologically...

Pages List

General info about this blog...