How can I replicate this loop in cfscript (for use in cf10 / railo)

201 views Asked by At

I have this working nicely in tag format, but am trying to migrate everything into cfscript. How can I do this one? (essentially, it loops over from date1 to date2, and needs to be in 15 minute intervals.

<cfset from=now()>
<cfset to=dateadd("d", 1, from)>
<cfloop from="#from#" to="#to#" index="i" step="#CreateTimeSpan(0,0,15,0)#">
 ...stuff...
<cfloop>

It's how to specify the step bit which is getting me..

2

There are 2 answers

1
Jarede On BEST ANSWER
<cfscript>
  variables.dtNow = now();
  variables.dtTmrw = dateAdd('d',1,variables.dtNow);

  do {
    variables.dtNow = dateAdd('n',15,variables.dtNow);
    writeOutput(variables.dtNow);
  } while(variables.dtNow neq variables.dtTmrw);
</cfscript>
2
Adam Cameron On

@Jarede's answer certainly gives you a loop which performs the same iterations with the same values as your requirement, but it's not really equivalent to the tag version. This is the closest to your example:

from    = now();
to        = dateadd("d", 1, from);
step    = CreateTimeSpan(0,0,15,0);
for (i=from; i <= to; i+=step){
    // ... stuff ...
}

If you're incrementing (or decrementing) and index value, use a for() loop, If your condition is not based around an index value, use a do or a while loop.

As I mentioned in a comment above, if you are not familiar with CFScript, you need to be. I recommend reading this, thoroughly: CFScript. It's the only complete documentation of CFScript I'm aware of. If you notice any omissions... send me a pull request.