Date Formatting in actionscript

2019-07-20 21:00发布

问题:

I have the following problem: I take a date (as a string data type) from the user. Now, I want to know if there is a a function in actionscript that will convert it to a date format. Right now, I am just parsing the string and concatenating the pieces back together. Ie:

changeDateString = date.getFullYear().toString() + '/' + (date.getMonth()+1).toString() + '/' + date.getDate();

But for months like May, it will return "5" and not "05". I have similar problems for days like "9" or "7." Is there something in the library that will do this for me? (For the moment, I can go ahead and manually concatenate the "0" in front, but this seems like a hassle to do.)

I know this is a simple question, but I a novice.

Thanks.

回答1:

Use a date formatter for that:

http://help.adobe.com/en_US/FlashPlatform/beta/reference/actionscript/3/mx/formatters/DateFormatter.html

You configure your formatter to use the format based on the types listed and use it to output your date.

var formatter:DateFormatter = new DateFormatter();
formatter.formatString = "m/d/Y";
var example:Date = new Date(2010, 0, 5, 10, 25);
trace(formatter.format(example));  // Displays: 01/05/2010

Just use the Pattern Letter/Description grid in the docs to find the right format for your needs.