Previous Page
Next Page

Recipe 14.9. Parsing a Date from a String

Problem

You want to create a Date object from a string.

Solution

Use the parse( ) method of a DateFormat object.

Discussion

ActionScript does not provide native methods for parsing a string into a Date object, and in many cases, that doesn't pose any difficulty. 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 the parse method of the custom ascb.util.DateFormat class. The 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.

To use the DateFormat class, you need to create an instance with the constructor. When you create the instance, you should pass a mask string to the constructor as a parameter. Recipe 14.4 has more details on creating a mask string:

var formatter:DateFormat = new DateFormat("m/d/Y");

Once you've created a DateFormat instance, you can next call the parse( ) method. Pass it a string in the format specified by the mask, and it parses the date, returning a new Date instance:

// Displays: Sat May 1 00:00:00 GMT-0700 2010 (timezone offset may vary)
trace(formatter.parse("05/01/2010"));

formatter.mask = "m/d/Y 'at' h:i a";

// Displays: Sat May 1 22:25:00 GMT-0700 2010 (timezone offset may vary)
trace(formatter.parse("05/01/2010 at 10:25 PM"));

See Also

Recipe 14.4


Previous Page
Next Page
Converted from CHM to HTML with chm2web Pro 2.85 (unicode)