Looping over Date Ranges
- April 16, 2009 2:21 PM
- ColdFusion
- Comments (3)
Learned something new today: <cfloop> can be used to loop over date ranges. This is because dates are represented as integer values in ColdFusion, so incrementing a date by 1 day is really incrementing the underlying value by 1. This means that you can do this:
<cfset startDate = Now() />
<cfset endDate = DateAdd("ww", 1, startDate) />
<cfloop from="#startDate#" to="#endDate#" index="date">
<cfoutput>#DateFormat(date, "mm-dd-yyyy")#</cfoutput><br />
</cfloop>
<cfset endDate = DateAdd("ww", 1, startDate) />
<cfloop from="#startDate#" to="#endDate#" index="date">
<cfoutput>#DateFormat(date, "mm-dd-yyyy")#</cfoutput><br />
</cfloop>
And get this:
04-16-2009<br />
04-17-2009<br />
04-18-2009<br />
04-19-2009<br />
04-20-2009<br />
04-21-2009<br />
04-22-2009<br />
04-23-2009<br />
04-17-2009<br />
04-18-2009<br />
04-19-2009<br />
04-20-2009<br />
04-21-2009<br />
04-22-2009<br />
04-23-2009<br />
Everyone else probably knew this, but I thought it was really nifty :)
Comments
Yeah, it defaults to 1, but you can set it to anything, including other whole numbers (ex. 2 = 2 days) or even time spans:
step="#CreateTimeSpan( 1, 0, 30, 0 )#"
A while back, I created a custom tag that allowed for date-part-oriented looping. If you're interested, check it out:
http://www.bennadel.com/blog/893-Date-Looping-Usin...