Looping over Date Ranges

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>

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 />

Everyone else probably knew this, but I thought it was really nifty :)

 

Comments

Ben Nadel's Gravatar Add the "step" value for days and you're really cooking!
Jon Hartmann's Gravatar Ben, even without a step value, the default seem to be to increment by 1 day. Setting the step to 1 produced no difference in result. Setting the loop to 7 gave me two dates, the beginning and end of the range. I was kind of hopeful that you were meaning that I could set the step to "d" or "ww" like the date part designators for DateAdd(), but unfortunately not.
Ben Nadel's Gravatar @Jon,

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...
Comments are not allowed for this entry.
Jon Hartmann, July 2011

I'm Jon Hartmann and I'm a Javascript fanatic, UX/UI evangelist and former ColdFusion master. I blog about mysterious error messages, user interface design questions, and all things baffling and irksome about programming for the web.

Learn more about me on LinkedIn.