Raymond Camden's Blog Rss

Comparing centuries of dates

7

Posted in ColdFusion | Posted on 05-29-2008 | 2,156 views

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:

view plain print about
1<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.

view plain print about
1<cfoutput>
2#year(d1) \ 100#
3</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

[Add Comment] [Subscribe to Comments]

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!
I did mention the \ operator in the blog entry. Did I do it too quickly?
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 :-)
Home time is pub time, right? ;)
Too right! Just goes to show that ColdFusion developers are the same all over the world :)
"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().
You are right Duncan! Sorry about that folks.

[Add Comment] [Subscribe to Comments]