Entries for month: April 2008

Looping Through Time

ColdFusion No Comments »

I just came across some existing code in a "revamping" project I'm working on that just didn't feel right. It was to produce a select dropdown of hourly time ranges in a day, in 24hr format: 00:00-00:59, 01:00-01:59, etc.

This was being achieived by using 2 loops. A first looping from 0-9 and building the times using 0#i#:00 - 0#i#:59. Then another loop from 10-23 and changing it slightly to be #i#:00 - #i#:59. Clunky, eh?

First thing that popped into my head was that it could easily be created with 1 loop from 0-23 using numberFormat() to include the leading 0 when required. But then I seemed to remember being told ColdFusion can loop over dates/times.

Not ever trying this before, I decided not to jump straight on Google but to open up my trusty play.cfm to have a try at it.

And strangley enough, it only took 2mins and worked first time.

<cfset fromTime = createTime(00,00,00) />
<cfset toTime = createTime(23,59,59) />
<cfset timeSpan = createTimeSpan(0,0,60,00) />
<select>
	<option value="">- Select Time -</option>
	<cfloop from="#fromTime#"to="#toTime#" index="i" step="#timeSpan#">
	<cfoutput>
	<option value="#LStimeFormat(i)# - #LStimeFormat(dateAdd('n',59,i))#">#LStimeFormat(i)# - #LStimeFormat(dateAdd('n',59,i))#</option>
	</cfoutput>
	</cfloop>
</select>

Pretty self explanitory really, create 2 proper timestamps and a timespan. Loop from and to the timestamps using the timespan as the step. Then just format the index variable as required. Job Done.

Powered by Mango Blog. Design and Icons by N.Design Studio
RSS Feeds