在ColdFusion中寻找类似this的功能,允许我将日期显示为“10分钟前”或“2天前”或“一个月前”。
答案 0 :(得分: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>
答案 1 :(得分:5)
您可以在cflib.org上试用此udf:http://cflib.org/udf/ago