ColdFusion Relative Time Script UDF

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.

<cfscript> function relativeTime(pastdate) { var delta = dateDiff("s", pastDate, now());

if(delta &lt; 60) {
    return "less than a minute ago";
} else if(delta &lt; 120) {
    return "about a minute ago";
} else if(delta &lt; (45*60)) {
    return round(delta/60) & " minutes ago";
} else if(delta &lt; (90*60)) {
    return "about an hour ago";
} else if(delta &lt; (24*60*60)) {
	return round(delta/3600) & " hours ago";
} else if(delta &lt; (48*60*60)) {
    return "1 day ago";
} else {
	return round(delta/86400) & " days ago";
} } &lt;/cfscript&gt;

<cfset pastdate = dateAdd(“n”, -9400, now())> <cfoutput>Paris had dignity #relativeTime(pastdate)#</cfoutput> </code>

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

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. You can even buy me a coffee!

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

Comments