2010-04-20 62 views

回答

10

虽然比UDF没有本质上的区别,我喜欢this guy's approach。不严格测试的,但你也可以做这样的事情:

编辑你没有提到的一个版本,所以我假定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> 
+0

为什么你需要声明'var x'? – 2014-10-10 11:08:59

+1

它是一个函数本地循环变量,所以它也必须是var/local作用域。 – Leigh 2014-10-10 11:34:23

5

您可以从cflib.org试试这个UDF:http://cflib.org/udf/ago

+1

我不知道为什么do..while循环是需要。他可能只是回来而不是休息。 – Henry 2010-04-20 23:30:08

+0

我自己并没有使用它,但它至少起点为 – Antony 2010-04-20 23:33:10