Warning: This blog entry was written two or more years ago. Therefore, it may contain broken links, out-dated or misleading content, or information that is just plain wrong. Please read on with caution.
In previous articles I have demonstrated how to find the date of the first instance of a weekday in a month, and how to number the weeks in a month and find what week number a particular date falls on.
These combined with the built in ColdFusion's built in date functions cover most situations you could encounter when doing reports based on weeks numbers. However sometimes it is necessary to base a week number off the date off the first instance of a weekday in the month.
Week Number Based Off The First Business Day
For example using the previous method of week numbering, if the first day of the month fell on a Saturday then the first week in the month would be a single day as the next day Sunday would be the start of a new week. However in reality you might want the week numbering to be based off the first business day in the month (Monday).
So how do we do this. Well this is a little function I wrote recently to solve exactly this problem.
<cffunction name="baseMondayWeekOfMonth" access="public" output="true" hint="Gets the week number of a given date based off the first monday in the month">
<cfargument name="testDate" type="date">
<!--- Get the week number using standard calculation --->
<cfset var weekNumber = weekOfMonth(testDate)>
<!--- Find the date of the first monday --->
<cfset var firstMonday = firstInstanceOfWeekDayInMonth(arguments.testDate,2)>
<!--- Find what the week number of the first mondaywould normally be --->
<cfset var weekOfFirstMonday = weekOfMonth(firstMonday )>
If the first monday occurs on the second week based on the normal calculation
and the current week number is greater than 1 then decrement by 1
<cfif weekOfFirstMonday GT 1 AND weekNumber GT 1>
<cfset weekNumber = weekNumber - 1>
To accomplish this I simply used the previous calculations to find the normal week numbering system plus the first instance of the desired base day Monday and if the first Monday is in week 2 shift the week numbering by 1 position to compensate. I know simple right.