I could be overlooking something, but Flash / AS3 seems to be missing basic date formatting functionality. How do I get a formatted string from a Date
? There's a few options like .toLocaleDateString()
and .toUTCString()
, but that a bit limiting, to say the least.
So, how do I format a Date
object in AS3?
Flash Player 10.1 added a DateTimeFormatter as part of the flash.globalization package. It's flexible but not well documented.
import flash.globalization.DateTimeFormatter;
var d:Date = new Date();
var dtf:DateTimeFormatter = new DateTimeFormatter("en-US");
dtf.setDateTimePattern("yyyy-MM-dd 'at' hh:mm:ssa");
trace(dtf.format(d));
// 2012-06-06 at 09:58:46PM
Here's a simple example of a custom format:
public static function getDateIso8601Long(date:Date):String {
var str:String = date.getFullYear().toString()
str = str +"-"+ ((String((date.getMonth()+1)).length == 1)?"0"+(date.getMonth()+1):(date.getMonth()+1)).toString()
str = str +"-"+ ((date.getDate().toString().length == 1)?"0"+date.getDate():date.getDate()).toString()
str = str +"T"+ ((date.getHours().toString().length == 1)?"0"+date.getHours():date.getHours()).toString()
str = str +":"+ ((date.getMinutes().toString().length == 1)?"0"+date.getMinutes():date.getMinutes()).toString()
str = str +":"+ ((date.getSeconds().toString().length == 1)?"0"+date.getSeconds():date.getSeconds()).toString()
var ms:String = date.getMilliseconds().toString()
while (ms.length < 3)
ms = "0"+ms
str = str+"."+ms
var offsetMinute:Number = date.getTimezoneOffset()
var direction:Number = (offsetMinute<0)?1:-1
var offsetHour:Number = Math.floor(offsetMinute/60)
offsetMinute = offsetMinute-(offsetHour*60)
var offsetHourStr:String = offsetHour.toString()
while (offsetHourStr.length < 2)
offsetHourStr = "0"+offsetHourStr
var offsetMinuteStr:String = offsetMinute.toString()
while (offsetMinuteStr.length < 2)
offsetMinuteStr = "0"+offsetMinuteStr
str = str+((direction == -1)?"-":"+")+offsetHourStr+":"+offsetMinuteStr
return str
}
Unfortunately I don't think you are overlooking anything in terms of native support. There is this project which seems to offer a bit more flexibility, however I have not ever got round to working with it in any depth so I can't vouch for it. The project I am currently working on has a 500 line (and counting) DateUtil class as a result..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With