tags:

views:

175

answers:

3

In ActionScript, how do you get the day number at the end of the month?

  • June Example

    getEndOfMonth() returns 30;

  • July Example

    getEndOfMonth() returns 31;

A: 

In many languages, you can achieve this by getting a date value for the zeroth day of the following month, then working it out from that. So maybe try:

var d:Date = new Date(2009,7,0);
var day:Number=d.getDate();

If that doesn't work, you can get the first day of the following month, and subtract a day

var millisecondsPerDay:int = 1000 * 60 * 60 * 24;
var d:Date = new Date(2009,7,1);
d.setTime(d.getTime() - millisecondsPerDay);
var day:Number=d.getDate();
Paul Dixon
Since I won't always be running in July, I changed that to var d:Date = new Date(); d.setMonth(d.getMonth()+1); d.setDate(0); var day:Number = d.getDate();Ugly, but works. I wonder if there is something better... whatever. Thanks, even if you look like this guy from my uni rugby team that used to punch me randomly.
stevedbrown
Why calculate something that is known? LUTs are much faster and cleaner...
LiraNuna
This is something that happens once when the app loads, not all the time. Technically, action script months start at 1, but I know what you mean. For some apps it's worth doing arrays and sometimes not so much. In my case, the calc'ed answer is fine, sometimes it would be better to do the array.
stevedbrown
The first solution relies on an undocumented implementation detail of Date's constructor. Strictly speaking it is invalid use of the Date API. The ActionScript reference at http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/Date.html#Date() clearly states that the date argument must be a value between 0 and 31. While this is unlikely to change in the future, I'd be wary to use this.
Sebastian Rittau
A: 

There are only twelve of them (and one special case for leap years)--it wouldn't be that bad to just write it out.

zenazn
+3  A: 
static public function getEndOfMonth(month:uint, isLeap:Boolean = false):uint
{
    return [31, 28 + isLeap, 31, 30, 30, 31, 31, 30, 31, 30, 31][month];
}

You can add an object called Month with const uints, for example Month.JANUARY == 0 and so on, encapsulate it etc etc...

LiraNuna
I still don't want to be writing date logic, but thanks for the 110%... +1 anyways.
stevedbrown