Strange weeknumbers in ColdFusion
We had a strange problem in ColdFusion recently, using weeknumbers and dates. In ColdFusion, you can use the Week() function to determine what weeknumber the week of any given date has. A very useful function you’d say. However, January 1st 2010 will present a very weird problem.
The international ISO 8601, containing the international standard about date and time, states that the first week of the year with at least four days in it (weeks starting on Monday and ending on Sunday) is called week #1. However, if you try this in ColdFusion, then you’ll find that the weeknumber is going from 53 to 2. There is no week #1 in 2010 according to ColdFusion!
To solve this I wrote the function below, feel free to use it.
<cffunction name="getWeekNumber" returntype="numeric" output="no"> <cfargument name="ts" type="date" required="true" hint="A Date object of which to determine the weeknumber."> <cfset var local = structnew()> <cfset local.refts = dateadd('d', 1, arguments.ts)> <cfset local.weekyear = year(dateadd('d', 2, local.refts))> <cfset local.getfirst = createdate(year(arguments.ts), 1, 4)> <cfif dayofweek(local.getfirst) neq 2> <cfloop condition="dayofweek(local.getfirst) neq 2"> <cfset local.getfirst = dateadd('d', -1, local.getfirst)> </cfloop> </cfif> <cfset local.daysinbetween = datediff('d', local.getfirst, arguments.ts)> <cfset local.weeknumber = fix(local.daysinbetween/7)+1> <cfreturn local.weeknumber> </cffunction>

One comment to “Strange weeknumbers in ColdFusion”
Ron Pasch
18-04-2012
at 16:01
This possibly returns wrong weeknumbers in leapyears.
I posted a custom function for this on CFLib.org a long time ago that takes leapyears into account as well.
http://www.cflib.org/index.cfm?event=page.udfbyid&udfid=1002
Leave a reply