O'Reilly logo

ActionScript 3.0 Cookbook by Joey Lott, Darron Schall, Keith Peters

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

Calculating Elapsed Time or Intervals Between Dates

Problem

You wan t to calculate an elapsed time, elapsed date, or relative time.

Solution

For simple elapsed time, you can add and subtract from the epoch milliseconds, or use the value returned by getTimer(). For more complex conversions, use the methods of the custom DateUtilities class.

Discussion

For simple conversions such as adding or subtracting an hour, day, or week to or from a date, simply add or subtract from the date’s epoch milliseconds value. For this purpose, note that a second is 1,000 milliseconds, a minute is 60,000 milliseconds, an hour is 3,600,000 milliseconds, a week is 604,800,000 milliseconds, and so on. Unless you have a knack for remembering these conversion values, storing them as constants is a convenient option. The constants have already been defined in the custom ascb.util.DateUtilities class as follows:

public static const MILLISECOND:Number = 1;
public static const SECOND:Number = MILLISECOND * 1000;
public static const MINUTE:Number = SECOND * 60;
public static const HOUR:Number = MINUTE * 60;
public static const DAY:Number = HOUR * 24;
public static const WEEK:Number = DAY * 7;

You can use the Date.time property to retrieve a date’s current value in epoch milliseconds, and then assign a new value to the time property relative to the current value. The following example adds one day to a given Date object:

var example:Date = new Date(2010, 0, 5, 10, 25); // Displays: Tue Jan 5 10:25:00 GMT-0800 2010 trace(example); ...

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