Tuesday, May 18, 2010

Get number of weeks within fiscal year

The other day I found myself looking for a solution to find the week number we are in within a given fiscal year. Here's the solution I came up with with a snippet from my code:

Date.prototype.getWeek = function (dowOffset)
{
/*getWeek() was developed by Nick Baicoianu at MeanFreePath: http://www.meanfreepath.com */
dowOffset = typeof(dowOffset) == 'int' ? dowOffset : 0; //default dowOffset to zero
var newYear = new Date(this.getFullYear(),0,1);
var day = newYear.getDay() - dowOffset; //the day of week the year begins on
day = (day >= 0 ? day : day + 7);
var daynum = Math.floor((this.getTime() - newYear.getTime() - (this.getTimezoneOffset()-newYear.getTimezoneOffset())*60000)/86400000) + 1;
var weeknum;
//if the year starts before the middle of a week
if(day < 4)
{
weeknum = Math.floor((daynum+day-1)/7) + 1;
if(weeknum > 52)
{
nYear = new Date(this.getFullYear() + 1,0,1);
nday = nYear.getDay() - dowOffset;
nday = nday >= 0 ? nday : nday + 7;
/*if the next year starts before the middle of
the week, it is week #1 of that year*/
weeknum = nday < 4 ? 1 : 53;
}
}
else
{
weeknum = Math.floor((daynum+day-1)/7);
}
return weeknum;
}
var todaysDate = new Date();
var currentFiscalYear = todaysDate.getFullYear() - 1;
var numberWeeks;
if(todaysDate.getMonth() > 8 && todaysDate.getMonth() < 11)
{
currentFiscalYear = todaysDate.getFullYear();
}
var beginFiscalDate = new Date();
beginFiscalDate.setFullYear(currentFiscalYear,8,1);
var endFiscalDate = new Date();
endFiscalDate.setFullYear(currentFiscalYear+1,7,31);
var currYearBegFiscalYear = new Date();
currYearBegFiscalYear.setFullYear(todaysDate.getFullYear(), 8,1);
if(todaysDate.getFullYear() > beginFiscalDate.getFullYear()) //Check to see if today comes after september of the current year
{
var decFiscalYear = new Date();
decFiscalYear.setFullYear(currentFiscalYear,11,31);
numberWeeks = todaysDate.getWeek() + (decFiscalYear.getWeek() - beginFiscalDate.getWeek());
}
else
{
numberWeeks = todaysDate.getWeek() - beginFiscalDate.getWeek();
}