Raymond Camden's Blog Rss

ColdFusion Relative Time Script UDF

4

Posted in ColdFusion | Posted on 12-19-2007 | 2,881 views

A few minutes ago a user in the ColdFusion IRC channel asked about an ActionScript relative time script. What is a relative time script? It translates something like "December 10" to "8 days ago". Turns out Google found a bunch of examples here. I took the first example, a JavaScript one, and rewrote it. This version is ColdFusion 8 only since it uses <, but you could change that in about 2 nanoseconds for a cf7 and earlier version. I'll add this up to CFLib a bit later probably.

view plain print about
1<cfscript>
2function relativeTime(pastdate) {
3    var delta = dateDiff("s", pastDate, now());
4
5    if(delta
< 60) {
6     return "less than a minute ago";
7    } else if(delta < 120) {
8     return "about a minute ago";
9    } else if(delta < (45*60)) {
10     return round(delta/60) & " minutes ago";
11    } else if(delta < (90*60)) {
12     return "about an hour ago";
13    } else if(delta < (24*60*60)) {
14        return round(delta/3600) & " hours ago";
15    } else if(delta < (48*60*60)) {
16     return "1 day ago";
17    } else {
18        return round(delta/86400) & " days ago";
19    }
20}
21</cfscript>
22
23
24<cfset pastdate = dateAdd("n", -9400, now())>
25<cfoutput>Paris had dignity #relativeTime(pastdate)#</cfoutput>

I'll update the wiki too (got to represent the ColdFusion!)

Comments

[Add Comment] [Subscribe to Comments]

Thanks Ray,

However, I'm concerned that your example is redundant. Not sure Ms Hilton ever had dignity! :)
This syntax errors in BD7 too. Found out using Project Tracker which incorporated it and couldn't be started.

For the sake of one character, best to change all "<" to "LT" so it works in everything.
Well, I did clearly point out it was cf8 only because of the <. Folks are welcome to mod it.
Thanks Ray, I'm now using this in a Twitter RSS feed reader. Mixed in GetTimeZoneInfo() to get our Australian offset hours and it's working great!