[ ACTIONSCRIPT ] Determining the Number of Days in a Month
Actionscript’s Date object has many useful attributes like “FullYear”, “Month”, “Day” and so on. However it doesn’t have a way to tell you how many days there are in the month that date is in. This is something that you may find useful, as you may need to loop over the days of a month for various reasons. While Actionscript doesn’t provide a built in to give you this value, its easy enough to use what it does offer to get the information you need.
First, it seems that Actionscript treats the days in a month like a list of numbers in a circle. In other words, if AS counted out loud starting at 1, when it got to the end of the month, it would automatically start back over at 1 (the first of the month). Now for the code:
var LastDayOfMonth:Number = new Date(2008, 3, 0).getDate() as Number;
//Trace should yield 31
trace(LastDayOfMonth);
So that’s it. The one little line. Seems all too easy doesn’t it. Let me explain.
First, we create a new variable with a type of number. In the end, we want to know the number value of the last day of the month.
Next, we create a new Date object. I hard coded March 0, 2008. You could pass in variables for the values or whatever you need to do.
Now you’re probably wondering about the “0″ in that Date I just entered. Remember what I said about counting the days and at the end you start back over at 1 for the first of the month. Well following that logic, if 1 is the first of the month, then 0 is the last day of the month. No really! If you don’t believe me, set that value to -1 and you’ll get the second to last day of the month. So really we just tricked Actionscript into creating a Date object for the last day of March.
Now all we need is that one number value, so we call the toDate() method of the date object (AS refers to the day number as “date”, not to be confused with the Date object which is a time stamp).
Finally, to be safe, I add the “as Number” to the end to make sure a number is passed to my Number variable, LastDayOfMonth.
So thats it. Now, if you want to loop over the days of a month, and perhaps that month changes dynamically, then the last day of the month value will will tell your loop when to stop.
:) Happy coding!
About this entry
You’re currently reading “[ ACTIONSCRIPT ] Determining the Number of Days in a Month,” an entry on :: M o l a r o ::
- Published:
- February 7, 2008 / 11:02 pm
- Category:
- Web Design / Development
- Tags:
- Actionscript, Flex


10d Comments
Jump to comment form | comment rss [?]