dev.e.loper
dev.e.loper

Reputation: 36054

Creating ActionScript Date object from MySQL UTC timestamp string

I'm storing Date in datetime column of MySQL table. I'm inserting current date by calling MySql's UTC_CURRENTDATE. When I retrieve it, it's in following string format: "2012-07-24 12:59:58"

When I try to create a Date object in Action Script by doing the following:

var dateNum:Number = Date.parse(createDate); // this gives me NaN
var createDate:Date = new Date(dateNum);

Date.parse("2012-07-24 12:59:58") gives NaN

Solution: Following Jason's advice, I'm doing the following:

Select a UNIX_TIMESTAMP(CREATE_DATE) which returns me seconds since '1970-01-01 00:00:00' UTC. Then do following in Actionscript:

var createDate:Date = new Date();
var offset:Number = createDate.getTimezoneOffset() * 60 * 1000; 
createDate.time = parseInt("1343174921") * 1000 - offset;

This gives me the right date.

Upvotes: 2

Views: 1149

Answers (1)

Jason Sturges
Jason Sturges

Reputation: 15955

Although I'm sure there's a more elegant approach; clearly you could implement a parse function such as:

public static function parse(date:String):Date
{
    var split:Array = date.split(" ");
    var splitDate:Array = split[0].split("-");
    var splitTime:Array = split[1].split(":");

    return new Date(splitDate[0],
                    splitDate[1] - 1,
                    splitDate[2],
                    splitTime[0],
                    splitTime[1],
                    splitTime[2]);
}

Called as:

var date:Date = parse("2012-07-24 12:59:58");

Instead of handling MySQL DATETIME, your SQL statements could convert to timestamps which ActionScript Date constructor would accept milliseconds since epoch.

Frameworks such as CASA Lib have nice date utility functions.

Upvotes: 3

Related Questions