Ask Ben: Formatting A Date Span In ColdFusion

<cffunction
	name="DateSpanFormat"
	access="public"
	returntype="string"
	output="false"
	hint="I take two dates and format their time span.">
 
	<!--- Define arguments. --->
	<cfargument
		name="From"
		type="any"
		required="true"
		hint="I am the from date/time."
		/>
 
	<cfargument
		name="To"
		type="any"
		required="true"
		hint="I am the to date/time."
		/>
 
	<!--- Define the local scope. --->
	<cfset var LOCAL = {} />
 
	<!---
		Check to see if the dates are the same year. If they are,
		then we can format a compact time span. If they are not
		the same year, then we have not special format.
	--->
	<cfif (Year( ARGUMENTS.From ) EQ Year( ARGUMENTS.To ))>
 
		<!---
			Now that we know the dates are the same year, let's
			see how compact we can format the span. If they are
			the same month, we can go even smaller.
		--->
		<cfif (Month( ARGUMENTS.From ) EQ Month( ARGUMENTS.To ))>
 
			<!---
				Return same-month span.
				Example: June 12-30, 2009
			--->
			<cfreturn (
				DateFormat( ARGUMENTS.From, "mmmm d" ) &
				"-" &
				DateFormat( ARGUMENTS.To, "d, yyyy" )
				) />
 
		<cfelse>
 
			<!---
				Return same-year span.
				Example: June 12 - December 12, 2009
			--->
			<cfreturn (
				DateFormat( ARGUMENTS.From, "mmmm d" ) &
				"-" &
				DateFormat( ARGUMENTS.To, "mmmm d, yyyy" )
				) />
 
		</cfif>
 
	<cfelse>
 
		<!--- Just return a two-part date span format. --->
		<cfreturn (
			DateFormat( ARGUMENTS.From, "mmmm d, yyyy" ) &
			" - " &
			DateFormat( ARGUMENTS.To, "mmmm d, yyyy" )
			) />
 
	</cfif>
</cffunction>

For Cut-and-Paste