Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relative Dates in ColdFusion

Tags:

coldfusion

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".

like image 469
Larsenal Avatar asked Apr 20 '10 23:04

Larsenal


2 Answers

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>
like image 185
Leigh Avatar answered Oct 20 '22 17:10

Leigh


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

like image 5
Antony Avatar answered Oct 20 '22 17:10

Antony