10.1. Finding the Current Date and Time

Problem

You want to know the current date and time.

Solution

Create a new date using the Date( ) constructor with no parameters. Alternatively, use a CGI script or any other server-side language to return the server time, and create a new Date object from that value.

Discussion

The date and time that ActionScript can calculate on its own is based on the client computer’s date and time settings. Therefore, if the user’s computer has the incorrect time, so will the Flash movie. With that caveat in mind, you can retrieve the current client-side date and time by creating a new Date object using the Date( ) constructor with no parameters, as follows:

// Create a new Date object.
today = new Date(  );

// Displays client-side date and time
trace(today);

Warning

Avoid the temptation to name your date variable date. Unlike in JavaScript, ActionScript identifiers (including variable and class names) are case-insensitive. Date is the name of the constructor function for the Date class; therefore, naming a variable date disables the Date constructor.

If an active Internet connection is available, the Flash movie can try to retrieve the date and time from a server. This technique can ensure more accurate dates and times. Although the server’s time settings might be inaccurate, at least the time will be consistent for all client movies.

The basic process when reading the time from a server is as follows:

  1. Create a CGI script on the web server that outputs a name/value ...

Get Actionscript Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.