Working with Fuzzy Dates and Times

You've probably seen those relative or "fuzzy" date displays on various sites across the internet, especially on sites like Twitter and Facebook where they'll say "Just Now" or "13 minutes ago" rather than a traditional date-formatted string. It makes sense, after all that's how we speak to each other. For example, if you're meeting someone, if you're asked how long you'd been there, you don't say "I got here at 11:05:46 am". Instead, you say "I got here about 5 minutes ago."

Wanting similar functionality in a project I was working on, I looked around the web and sites like CFLib to see if I could find something similar. I couldn't, so I decided to write my own. The code for the function is below.  Although it could be a lot smarter and more international-friendly, it gets the basic job done.

<cffunction name="fuzzyDateDiff" access="public" output="false" returntype="string">
	<cfargument name="date1" type="date" required="true" />
	<cfargument name="date2" type="date" required="true" />
	<cfset var intDiffUnits = 0 />
	<!--- Seconds --->
	<cfif dateDiff("s",arguments.date1,arguments.date2) lt 60>
		<cfreturn "Just now" />
	</cfif>
	<!--- Minutes --->
	<cfset intDiffUnits = dateDiff("n",arguments.date1,arguments.date2) />
	<cfif intDiffUnits lt 60>
		<cfreturn "#intDiffUnits# minute#iif(intDiffUnits gt 1,de("s"),"")# ago" />
	</cfif>
	<!--- Hours --->
	<cfset intDiffUnits = dateDiff("h",arguments.date1,arguments.date2) />
	<cfif intDiffUnits lt 24>
		<cfreturn "#intDiffUnits# hour#iif(intDiffUnits gt 1,de("s"),"")# ago" />
	</cfif>
	<!--- Days --->
	<cfset intDiffUnits = dateDiff("d",arguments.date1,arguments.date2) />
	<cfif intDiffUnits lt 7>
		<cfreturn dateFormat(arguments.date1,"dddd") />
	</cfif>
	<!--- Weeks --->
	<cfset intDiffUnits = dateDiff("ww",arguments.date1,arguments.date2) />
	<cfif intDiffUnits is 1>
		<cfreturn "Last week" />
	<cfelseif intDiffUnits lt 4>
		<cfreturn "#intDiffUnits# weeks ago" />
	</cfif>
	<!--- Months/Years --->
	<cfset intDiffUnits = dateDiff("yyyy",arguments.date1,arguments.date2) />
	<cfif intDiffUnits lt 1>
		<cfreturn dateFormat(arguments.date1,"mmmm d") />
	<cfelse>
		<cfreturn dateFormat(arguments.date1,"mmmm d, yyyy") />
	</cfif>
</cffunction>

Basic usage fuzzyDateDiff (date1, date2)

If you want the result to be realitive to the current date and time, simply use now() for date2. Happy coding!

Digg Facebook reddit Google Bookmarks DZone

No comments yet.

(will not be published)
Leave this field empty: