10.3. Formatting the Date and Time


You want to display a formatted date and/or time value.


Use Date.toString( ), or create a custom Date.format( ) method that returns the date and time as a string in the requested format.


The Date.toString( ) method returns a user-friendly string version of the target Date object. For example:

// Displays: Mon May 26 11:32:46 GMT-0400 2003
trace(new Date().toString(  ));

Because ActionScript automatically invokes the toString( ) method on any object used in a string context, you can obtain the same result even if you omit toString( ), as in the following example:

// Also displays: Mon May 26 11:32:46 GMT-0400 2003
trace(new Date(  ));

You can rewrite the Date.toString( ) method to return a different date format:

Date.prototype.toString = function (  ) {
  return "Milliseconds since the Epoch: " + this.getTime(  );
// Both display: Milliseconds since the Epoch: 1053963542360
trace (new Date().toString(  ));
trace (new Date(  ));

However, a better approach is to implement a flexible, custom formatting method that accepts a parameter specifying the desired date format. Fortunately, there is a standard implementation for date formatting in languages such as Java, which you can imitate. Table 10-1 shows the symbols you should use in creating the formatting string that is passed to the custom format( ) method.

Table 10-1. Date and time symbols








Month in year

December or 12 (depends on context: ...

Get Actionscript Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.