views:

63

answers:

2

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?

+1  A: 

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 
    } 
Guillaume Malartre
I was kinda hoping not to have to invent my own wheel.
Sietse
Maybe look at different util class available in large framework/libraries(as3coreLib,Spring Actionscript1). I'm not certain of what you would like to do. Do you need only formatter or also calculator? A simple google search returned me many Actionscript 3 utility classes for Date calculation. Also, converting a Java date utility class to As3 would be trivial.http://github.com/mikechambers/as3corelib/blob/master/src/com/adobe/utils/DateUtil.as
Guillaume Malartre
+1  A: 

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..

DannyC