Epoch in ActionScript
A common requirement in programs is getting the number of seconds, milliseconds, or nanoseconds since the Unix epoch. Here’s how to do it in ActionScript.
package {
import flash.display.Sprite;
import flash.utils.getTimer;
public class Epoch extends Sprite {
public function Epoch() {
// Use getTimer() to get milliseconds since Flash was initialized
var now:Number = new Date().time;
trace(new Date(now));
// Get seconds since Unix epoch
trace(Math.floor(now / 1000));
// Get milliseconds since Unix epoch
trace(now);
// Get microseconds since Unix epoch (ActionScript doesn't support nanoseconds)
trace(now * 1000);
// Convert seconds since epoch to Date
trace(new Date(Math.floor(now / 1000) * 1000));
// Convert milliseconds since epoch to Date
trace(new Date(now));
}
}
}
Use new Date().time
to get the current time in milliseconds since the Unix epoch. ActionScript doesn’t have built-in methods for Unix time in seconds or nanoseconds, so we need to perform some calculations.
To run this ActionScript code, you would typically compile it into a SWF file and run it in a Flash Player or AIR runtime environment. The output would look something like this:
Wed Oct 31 16:13:58 GMT-0000 2012
1351700038
1351700038292
1351700038292000
Wed Oct 31 16:13:58 GMT-0000 2012
Wed Oct 31 16:13:58 GMT-0000 2012
Note that ActionScript’s Date
class doesn’t provide nanosecond precision, so we’ve used microseconds (multiplying milliseconds by 1000) as the closest alternative.
Next, we’ll look at another time-related task: time parsing and formatting.