10.7. Parsing a Date from a String

Problem

You want to create a Date object from a string.

Solution

Create a custom parseDate( ) method that parses the individual date components (year, month, etc.) from the string using regular expressions and then assembles a new date.

Discussion

ActionScript does not provide any native methods for parsing a string into a Date object. This limitation does not necessarily pose a problem. For example, Flash Remoting allows you to return native Date objects from other applications. Even if you are not working with Flash Remoting, you can pass values between Flash and other applications using Epoch seconds/milliseconds. However, if you need to parse a string into a date, you should use a custom parseDate( ) method. This method takes the string value as a parameter, parses out each of the date’s parts (the year, hour, etc.), and then returns a new Date object. Add the following code to your Date.as file for easy inclusion in other projects. The following code uses the custom RegExp class. See Recipe 9.6.

// You must include the third-party RegExp.as file from Recipe 9.6. One way to ensure
// this is to add #include "RegExp.as" to the Date.as file in which you also add the
// parseDate(  ) method.
#include "RegExp.as"

// This method also relies on the Date.months array from Recipe 10.2. Date.parseDate = function (dateStr) { // Create local variables to hold the year, month, date of month, hour, minute, and // second. Assume that there are no milliseconds ...

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.