Comparing centuries of dates

This is a cross post from something I just posted to the ColdFusion Cookbook, but since that site gets about a 100 hits a month or so, I figured I'd share it here as well.

Date comparisons are fairly easy in ColdFusion. One common task is to compare a date value to the current date and check if there is a match on the day, week, month, etc. For this entry we will consider comparing a date's century to the current century. This is a bit more complex. While ColdFusion has functions to retrieve parts of a date (seconds, minutes, day, month, etc) it does not have a function to return the century value. You can get this using a bit of math though.

Consider the following date:

<cfset d1 = createDate(2009, 1, 1)>

To get the century, you can first get the year, and then divide the value by 100, using the \ operator to round the result.

<cfoutput>
#year(d1) \ 100#
</cfoutput>

This results in 20 (technically we would call 2009 the 21st century, but we just need a unique value). You could then simply compare this value to the value you get using year(now()) to see if d1 is in the same century.

Comments

John Whish's Gravatar If at first glance anyone things "hey shouldn't that return 20.09" look again. The example uses \ (arithmetic div operator) not a / (division operator). Not that it caught me out of course!
# Posted By John Whish | 5/29/08 11:27 AM
Raymond Camden's Gravatar I did mention the \ operator in the blog entry. Did I do it too quickly?
# Posted By Raymond Camden | 5/29/08 11:28 AM
John Whish's Gravatar Raymond - I think you'll always be too quick for me! I skim read the post, focused on the code then got confused - it's home time here in the UK and the caffeine has worn off :-)
# Posted By John Whish | 5/29/08 11:39 AM
Raymond Camden's Gravatar Home time is pub time, right? ;)
# Posted By Raymond Camden | 5/29/08 11:41 AM
John Whish's Gravatar Too right! Just goes to show that ColdFusion developers are the same all over the world :)
# Posted By John Whish | 5/29/08 11:45 AM
duncan's Gravatar "using the \ operator to round the result"

That's slightly misleading; if it was really rounding it would turn 2051 to 21, not 20. It's just doing a DIV operation. I know you know that already, but it's as well making it clear in the article for those who don't know, so they don't think \ = Round().
# Posted By duncan | 5/30/08 3:09 AM
Raymond Camden's Gravatar You are right Duncan! Sorry about that folks.
# Posted By Raymond Camden | 5/30/08 6:04 AM