在ColdFusion中寻找类似this的功能,允许我在“10分钟前”或“2天前”或“一个月前”显示日期。ColdFusion中的相对日期
14
A
回答
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>
5
您可以从cflib.org试试这个UDF:http://cflib.org/udf/ago
为什么你需要声明'var x'? – 2014-10-10 11:08:59
它是一个函数本地循环变量,所以它也必须是var/local作用域。 – Leigh 2014-10-10 11:34:23