Looping over times in ColdFusion is the same exact thing as looping over dates in ColdFusion, but sometimes, people don't quite make the mental leap on their own. And so, I thought I would just quickly demonstrate that this was possible.
The key to looping over times is to understand that a time value is really just a fractional date value and that when looping over it, your loop increment (step value) should also be a fractional time value as well. In this case, we are going to loop from 8:00 AM to 5:00 PM using a one hour increment:
<!--- When looping over the hours in the day, we are going to use an index loop and for each iteration, we are going to increase the index by a single hour (the numeric timespan representing an hour fraction of the day). ---> <cfset dtHour = CreateTimeSpan( 0, <!--- Days. ---> 1, <!--- Hours. ---> 0, <!--- Minutes. ---> 0 <!--- Seconds. ---> ) /> <!--- When looping over the hours in the day, we can enter the start and end time as "readable" time. ColdFusion will automatically convert those time strings to their numeric equivalents for use within the index loop. ---> <cfloop index="dtTime" from="8:00 AM" to="5:00 PM" step="#dtHour#"> #TimeFormat( dtTime, "hh:mm TT" )#<br /> </cfloop>
Running the above gives us:
Notice that in order to get our CFLoop step value, we are building a time span object (returns a Double value) that is created using just a single hour. The mental leap to make here is that that time span value could be anything you want. It could be days, hours, minutes, or seconds.
Just remember, dates are numeric values. Because an indexed CFLoop is iterating over numeric values, ColdFusion accomplishes this by converting your date/time value for the from/to attributes to numeric values behind your back. Embrace this, do not fear it :)
Want to use code from this post? Check out the license.