This is a real quick post about Unix Timestamps, PHP, and ActionScript 3’s Date class.  When creating a new Date instance, you can pass in a Unix Timestamp into the Date constructor.

[sourcecode lang=”php”]

var myDate:Date = new Date( unix_timestamp_from_php );
trace( myDate.toString() );  // Invalid Date

[/sourcecode]

When I was working with this, I continually received Invalid date in my output window.  Looking into the matter, if you read php.net’s time() function description and then taking a look at livedocs Date class we’ll quickly see the problem.

From php.net’s time() description:

time

(PHP 4, PHP 5)

time — Return current Unix timestamp

Description

int timevoid )

Returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).

And then from livedoc’s Date() Class:

Date() Constructor

Constructs a new Date object that holds the specified date and time.

The Date() constructor takes up to seven parameters (year, month, …, millisecond) to specify a date and time to the millisecond. The date that the newly constructed Date object contains depends on the number, and data type, of arguments passed.

So PHP time() gives you a Unix Timestamp for the current time in Seconds, and AS3 wants a time in MiliSeconds.

Here’s the fix:

[sourcecode lang=”php”]

var myDate:Date = new Date( unix_timestamp_from_php * 1000 );
trace( myDate.toString() ); // Tue Apr 28 13:09:32 GMT-0400 2009

[/sourcecode]

OR You could also simply typecast “unix_timestamp_from_php” to type Number() like so:

[sourcecode lang=”php”]

var myDate:Date = new Date( Number( unix_timestamp_from_php ) );
trace( myDate.toString() ); // Tue Apr 28 13:09:32 GMT-0400 2009

[/sourcecode]

Both of these work, I’m not 100% sure what happens in the Date constructor, but reading further in the Date livedocs, two bulletpoints stand out as to Why sending a String and a Number value give different results:

  • If you pass one argument of data type Number, the Date object is assigned a time value based on the number of milliseconds since January 1, 1970 0:00:000 GMT, as specified by the lone argument.
  • If you pass one argument of data type String, and the string contains a valid date, the Date object contains a time value based on that date.
Categories:

0 Comments

Leave a Reply

Avatar placeholder