CFLib.org – Common Function Library Project

firstXDayOfMonth(dayOfWeek, month, year)

Last updated July 6, 2014

Version: 1 | Requires: ColdFusion 9 | Library: DateLib

 
Rated 2 time(s). Average Rating: 2.5

Description:
Takes a day number, month number, and year. Returns a date object of the first occurrence of that day in the given month and year. For example, you want a date object for the first Wednesday in November, 2005. In this case, the function returns the date: 11/2/05.

Return Values:
The date of the first [dayOfWeek] of the specified month/year

Example:

view plain print about
Our Nov CFUG meeting is on #DateFormat(FirstXDayOfMonth(4,11,2005),"dddd, mmmm d")#

Parameters:

Name Description Required
dayOfWeek An integer in the range 1 - 7. 1=Sun, 2=Mon, 3=Tue, 4=Wed, 5=Thu, 6=Fri, 7=Sat. Yes
month Month value. Yes
year Year value. Yes

Full UDF Source:

view plain print about
<cfscript>
/**
 * Returns a date object of the first occurrence of a specified day in the given month and year.
 * v1.0 by Troy Pullis   
 * v1.1 by Adam Cameron (improved/simplified logic, added error handling)
 * 
 * @param dayOfWeek      An integer in the range 1 - 7. 1=Sun, 2=Mon, 3=Tue, 4=Wed, 5=Thu, 6=Fri, 7=Sat. (Required)
 * @param month      Month value.  (Required)
 * @param year      Year value. (Required)
 * @return The date of the first [dayOfWeek] of the specified month/year 
 * @author Troy Pullis (tpullis@yahoo.com) 
 * @version 1.1, July 6, 2014 
 */

date function firstXDayOfMonth(required numeric dayOfWeek, required numeric month, required numeric year){
    if (dayOfWeek 
< 1 || dayOfWeek > 7){
        throw(type="InvalidDayOfWeekException", message="Invalid day of week value", detail="the dayOfWeek argument must be between 1-7 (inclusive).");
    }
    var firstOfMonth    = createDate(year, month,1);
    var dowOfFirst        = dayOfWeek(firstOfMonth);
    var daysToAdd        = (7 - (dowOfFirst - dayOfWeek)) MOD 7;
    var dow = dateAdd("d", daysToAdd, firstOfMonth);
    return dow;
}
</cfscript>
blog comments powered by Disqus

Search CFLib.org


Latest Additions

Troy Pullis Troy Pullis added
firstXDayOfMonth
a while ago

Henry Ho Henry Ho added
arrayMap
a while ago

Henry Ho Henry Ho added
queryGetRow
a while ago

Tony Felice Tony Felice added
getRowFromQuery
a while ago

Top Rated

Darwan Leonardo Sitepu backupDatabase
Rated 5.0, 44 time(s)

Barney Boisvert indentXml
Rated 5.0, 12 time(s)

Rachel Lehman deAccent
Rated 5.0, 9 time(s)

Markus Schneebeli                                 ListRemoveByStri...
Rated 5.0, 4 time(s)

Created by Raymond Camden / Design by Justin Johnson