This ColdFusion function accepts a string or a date and tell you how long ago the date is from now. It comes in handy when needing to display the a message to the user.
You can call the fucntion like this:
-
<cfset mydate = "2009/12/03">
-
<cfinvoke component="MyComponent" method="howLongAgo" returnvariable="returnString"
-
inputdate="#mydate#" />
Here is the function that can be called from a cfc:
-
<cffunction name="howLongAgo" access="public" output="false" returntype="String">
-
<cfargument name="inputDate" required="true" type="Date" />
-
<cfset var datePartList = "yyyy,m,d,h,n,s" />
-
<cfset var datePartNameList = "year,month,day,hour,minute,second" />
-
<cfset var returnString = "" />
-
<cfset var diff = "" />
-
-
<cfloop from="1" to="#listlen(datePartList)#" index="thisPart">
-
<cfset diff = datediff(listgetat(datePartList,thisPart),arguments.inputDate,now()) />
-
<cfif diff GTE 1>
-
<cfset returnString = diff & " " & listgetat(datePartNameList,thisPart) />
-
<cfif diff GT 1>
-
<cfset returnString = returnString & "s" />
-
</cfif>
-
<cfset returnString = returnString & " ago" />
-
<cfreturn returnString />
-
</cfif>
-
</cfloop>
-
-
<cfreturn "0 seconds ago" />
-
</cffunction>
Finally, display the output:
<cfoutput>#returnString#</cfoutput>