0

I have a date like:

19/août/2016 (août = august)

And I have the following function which changes the month into a number:

function swapMonthForNumber(str:String):String {
    //do the same line of code for every item in the array
    for(var i:int=0;i<months.length;i++){
        //i is the item, which is 0 based, so we have to add 1 to make the right month number
        str = str.replace(months[i],String(+i+1));
    }

    //return the updated string
    return str;
}

str = swapMonthForNumber(mySharedObject.data.theDate);
trace("Php will use this date :"+str);

So str will be 19/8/2016, but I want str to be 19/08/2016 (adding a 0 before the 8).

How can I do this?

Jonny Henly
  • 4,023
  • 4
  • 26
  • 43
user5870211
  • 103
  • 8
  • What does `String(+i+1)` do? I've never seen that before. – Jonny Henly Aug 18 '16 at 22:26
  • 1
    You're probably going to want to check if the month is less than 10, and if so prepend a `"0"` to `String(i+1)` by doing `"0" + String(i+1)` (not sure if `+` is the concatenate operator in AS3, but I think it is). – Jonny Henly Aug 18 '16 at 22:42
  • @JonnyHenly in (+i+1) the leading + is redundant since it doesn't change the sign of i. – invisible squirrel Aug 18 '16 at 23:38
  • @dene : String(+i+1) was not edited but used by user5870211 in the original message I think. But for sure it's redundant ;) – tatactic Aug 27 '16 at 10:11

2 Answers2

1

Check out the reference of the Date class!

If forgot to mention this link : flash.globalization.DateTimeFormatter

DateTimeFormatter(requestedLocaleIDName:String, dateStyle:String = "long", timeStyle:String = "long")

Here is an example.

import flash.globalization.DateTimeFormatter;
var df:DateTimeFormatter = new DateTimeFormatter(LocaleID.DEFAULT, DateTimeStyle.SHORT, DateTimeStyle.NONE);
var currentDate:Date = new Date(2016,7,19);
var shortDate:String = df.format(currentDate);
trace (shortDate);

// output : 19/08/2016

DateTimeStyle

LocaleID

tatactic
  • 1,379
  • 1
  • 9
  • 18
0

Adding leading zeros to a number is commonly called zero padding.

Below is a function to do this, from the answer here.

public function zeroPad(number:int, width:int):String {
   var ret:String = ""+number;
   while( ret.length < width )
       ret="0" + ret;
   return ret;
}

In your swapMonthForNumber function, in the for loop, swap the code for this:

var month = zeroPad(i + 1, 2);
str = str.replace(months[i], month);
Community
  • 1
  • 1
invisible squirrel
  • 2,968
  • 3
  • 25
  • 26
  • @ dene : I don't know why you suggest to use a self made method since you may easily use the built in DateTimeFormatter Class? – tatactic Aug 27 '16 at 09:40
  • I'm not sure about the gain of time between the two methods... a getTimer() after a lot of conversions could probably show what is the best way to convert / format the Date Object in this case. – tatactic Aug 27 '16 at 10:51