ColdFusion Quickie - Last 12 Months

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 developer advocate. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support.

Lafayette, LA https://www.raymondcamden.com

Comments