tags:

views:

84

answers:

2

Looking for a function like this in ColdFusion, allowing me to show dates as "10 minutes ago" or "2 days ago" or "a month ago".

+2  A: 

You can try this udf from cflib.org: http://cflib.org/udf/ago

Antony
I don't know why a Do..While loop is needed. He could have just return it instead of break.
Henry
haven't used it myself, but it's a starting point at least
Antony
+2  A: 

Though not fundamentally different than the udf, I like this guy's approach. Not highly tested, but you could also do something like this:

Edit You did not mention a version, so I assumed CF8

<cffunction name="relativeDate" returnType="string" access="public" output="false">
    <cfargument name="theDate" type="date">
    <cfset var x        = "" />
    <cfset var diff  = "" />    
    <cfset var result   = "unknown" />    
    <cfset var dateNow  = now() />
    <cfset var codes    = [ "yyyy", "m", "ww", "d", "h", "n", "s" ] />
    <cfset var names    = [ "year", "month", "week", "day", "hour", "minute", "second" ] />

    <cfif dateCompare(arguments.theDate, now()) gt 0>
        <!--- replace with other code to handle future dates ....--->
        <cfthrow message="Future date handling not implemented">
    </cfif>

    <!--- check each date period  ...--->
    <cfloop from="1" to="#arrayLen(codes)#" index="x">
        <cfset diff = abs( dateDiff(codes[x], arguments.theDate, dateNow) ) />
        <!--- this is the greatest date period --->
        <cfif diff gt 0 >
            <cfif diff  gt 1>
                <cfset result = "about "& diff &" "& names[x] &"s ago" />
            <cfelseif names[x] eq "hour">
                <cfset result = "about an "& names[x] &" ago" />
            <cfelse>
                <cfset result = "about a "& names[x] &" ago" />
            </cfif>

            <cfbreak>
        </cfif>
    </cfloop>    

    <cfreturn result />
</cffunction>
Leigh