O'Reilly logo

Actionscript Cookbook by Joey Lott

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

10.3. Formatting the Date and Time

Problem

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

Solution

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

Discussion

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

Symbol

Meaning

Example

y

Year

2002

M

Month in year

December or 12 (depends on context: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required