A reader asked:
I'm really bad with programming so finding it very stressful at work. Could you please help me with something? I need to create a strings of months to do some stats and what I need is the previous 12 months. For example if current month is Sept then I need a loop to get all months from Sept last year to Aug this year. I've been scratching my head but couldnt work out a loop to do this. Please help me with this. I really appreciate your help. Thank you very much.
This is really simple (hence the quickie title) once you use ColdFusion's dateAdd function. As you can probably guess, it lets you take a date and then add an arbitrary amount of time to it. We can use this to add (or in our case, substract) from the current month. Here is a simple example:
<cfloop from="12" to="1" index="x" step="-1">
<cfset theMonth = dateAdd("m", -1 * x, now())>
<cfoutput>#dateFormat(theMonth,"mmmm yyyy")#<br></cfoutput>
</cfloop>
I looped from 12 to 1, and for each value, simply "added" it by using the negative value. The dateFormat was completely arbitrary. You can output the value anyway you want.
And a quick personal note to "a reader" (I didn't put her name in as it was rather unique), I feel your pain. If it makes you feel any better, I'm going through it as well, but it does get better with practice!
Archived Comments
How strange, I posted something very similar to this on http://www.coldfusioncookbo... a few weeks ago. "How do I create a "back dating" list of dates?" I needed to do the same thing and started writing line-and-lines of code for a few minutes until I realised life could be simpler with "dateadd()" in reverse.
What is strange?
The fact that I ran into this same issue, and needed a quick solution. I think yours is a bit more elegant since it loops from 12 to 1, stepping at -1. I think its way more understandable.
Ah ok. Thought I was missing something obvious. ;)
i was once doing something with cfloop and was pleased to find that 'from' and 'to' support negative numbers:
cfloop from="-1" to="-12" index="x" step="-1"