Finding the Day within the Year

Unlike many other great languages, ActionScript 3 does not have a method for finding a date’s day within a year. For example, February 10, 2008, is the 41st day in the year. Here is my solution:

function getDayOfYear(date:Date):Number {
var monthLengths:Array = new Array (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

// A leap year is divisable by 4, but not by 100 unless divisable by 400. Seriously.
if (((date.getFullYear() % 4 == 0) && (date.getFullYear() % 100 != 0)) || (date.getFullYear() % 400 == 0)) {
monthLengths[1] = 29;
trace ("leap year");
}

var dayInYear = 0;

// get day of year up to month
for (var i:Number = 0; i < date.getMonth(); i++) {
dayInYear += monthLengths[i];
}

// add day inside month
dayInYear += date.getDate();

// Start counting on 0 (optional)
dayInYear--;

return dayInYear;
}

trace(getDayOfYear(new Date("03/10/2008")));

And for giggles, here are the starting days for months in a non leap year:

var monthStartDays:Array = new Array(0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334);

Comments are closed.