Recipe 14.6. Converting Between DMYHMSM and Epoch Milliseconds


Problem

You want to convert between DMYHMSM format (days, months, years, hours, minutes, seconds, milliseconds) and epoch milliseconds.

Solution

Use the time property.

Discussion

Most of us are more comfortable thinking of dates and times in terms of their components such as hours, days, and years than working with epoch milliseconds or seconds. For example, it's much easier to give the time and date as 10:25 a.m., Tuesday, January 5, 2010 than to discuss the corresponding epoch value of 1,262,715,900,000 milliseconds. However, languages such as ActionScript store times in the epoch milliseconds (or epoch seconds) format. Therefore, it's important to be able to convert between different formats when displaying dates and times to users, or when sharing dates between applications that use different formats.

When constructing a date in ActionScript, you can use the DMYHMSM approach, as follows:

// Construct a date for 10:25 AM, Tuesday, January 5, 2010 var example:Date = new Date(2010, 0, 5, 10, 25);

ActionScript automatically performs the conversion and stores the date as the corresponding epoch milliseconds value. To retrieve that value, all you need to do is call the time property from the Date object, as follows:

// For Pacific Standard Time, displays: 1262715900000 // The output may vary depending on your time zone. trace(example.time);

You can pass the epoch seconds value returned by time to another application (such as a CGI script) or use it for performing date mathematics (see Recipe 14.1).

On the other hand, you may want to set a date using the epoch milliseconds. For example, in Recipe 14.1 the CGI script returns the current server time to Flash in epoch seconds (which needs to be converted to milliseconds by multiplying by 1,000). Also, when performing date mathematics you may want to set a date according to epoch milliseconds. You have two options for setting a date according to the epoch milliseconds. One choice is to pass the milliseconds value to the Date constructor as the only parameter, and the other is to assign the milliseconds value to the time property of an existing date. Both techniques are effectively the same.

// Construct a new Date object for 310:25 AM, Tuesday, January 5,  // 2010. Here, we use the value displayed in the Output window from // the preceding example. var example:Date = new Date(1262715900000); // Displays: Tue Jan 5 10:25:00 GMT-0800 2010 (timezone offset  // may vary) trace(example);

See Also

Recipe 14.1




ActionScript 3. 0 Cookbook
ActionScript 3.0 Cookbook: Solutions for Flash Platform and Flex Application Developers
ISBN: 0596526954
EAN: 2147483647
Year: 2007
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net