ColdFusion Quickie - Last 12 Months

This post is more than 2 years old.

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!

Raymond Camden's Picture

About Raymond Camden

Raymond is a senior developer evangelist for Adobe. He focuses on document services, JavaScript, and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA

Archived Comments

Comment 1 by Stefan le Roux posted on 9/17/2008 at 12:00 AM

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.

Comment 2 by Raymond Camden posted on 9/17/2008 at 12:29 AM

What is strange?

Comment 3 by Stefan le Roux posted on 9/17/2008 at 9:29 AM

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.

Comment 4 by Raymond Camden posted on 9/17/2008 at 3:10 PM

Ah ok. Thought I was missing something obvious. ;)

Comment 5 by db posted on 9/17/2008 at 5:37 PM

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"