The following example shows how you can parse an ISO format date (for more information, see http://www.w3.org/TR/NOTE-datetime) and convert it into a Date object in ActionScript using the String class’s replace() method and the static Date.parse() method.
Full code after the jump.
<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/02/02/parsing-iso-dates-with-flex-and-actionscript/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical"
verticalAlign="middle"
backgroundColor="white"
creationComplete="init();">
<mx:Script>
<![CDATA[
[Bindable]
private var d:Date;
private function init():void {
var isoStr:String = "2008-01-25T06:14:23Z";
d = isoToDate(isoStr);
formHeading.label = isoStr;
}
private function isoToDate(value:String):Date {
var dateStr:String = value;
dateStr = dateStr.replace(/-/g, "/");
dateStr = dateStr.replace("T", " ");
dateStr = dateStr.replace("Z", " GMT-0000");
return new Date(Date.parse(dateStr));
}
]]>
</mx:Script>
<mx:Form>
<mx:FormHeading id="formHeading" />
<mx:FormItem label="toString():">
<mx:Label text="{d.toString()}" />
</mx:FormItem>
<mx:FormItem label="toLocaleString():">
<mx:Label text="{d.toLocaleString()}" />
</mx:FormItem>
<mx:FormItem label="toUTCString():">
<mx:Label text="{d.toUTCString()}" />
</mx:FormItem>
</mx:Form>
</mx:Application>
View source is enabled in the following example.
A big thanks to Jon for helping me with the bug in my time-zone conversion.





Thanks for the code - a real life saver!
The only thing your function doesn’t deal with is the “null” ISO date: 0001-01-01T00:00:00. I would have expected this function to return a null Date object if it were passed this String.
public static function parseIsoDate(dateStr:String):Date { dateStr = dateStr.replace(/-/g, "/"); dateStr = dateStr.replace("T", " "); dateStr = dateStr.replace("Z", " GMT-0000"); const i:Number = Date.parse(dateStr); if (i < 0) { return null; } else { return new Date(i); } }David,
Great tip, thanks!
Peter
David, Peter
From my experience, if you can’t guarantee the given parameter dateStr is a valid date you should check for NaN using isNaN(i).
Many thanks for the useful example!
Have fun
Robert