Skip to content

Instantly share code, notes, and snippets.

@s7github
Last active December 16, 2015 15:49
Show Gist options
  • Save s7github/5458908 to your computer and use it in GitHub Desktop.
Save s7github/5458908 to your computer and use it in GitHub Desktop.
Coldfusion common date functions _ DateFormatPlus(date, mask, [customMaskValue1]) - Formats date with optional custom mask options. Each custom mask starts with $ sign and followed by a number in mainMask. For eg. $1 will be replaced by custom mask given as 1st parameter after mainMask parameter and $2 will be replaced by 2nd parameter after mai…
<cffunction name="DateFormatPlus" returntype="string" output="yes" hint="Formats date with optional custom mask options. Each custom mask starts with $ sign and followed by a number in mask. For eg. $1 will be replaced by custom mask value given as 1st parameter after mask parameter and $2 will be replaced by 2nd parameter after mask.">
<cfargument name="dateVal" required="yes" type="date" default="#now()#">
<cfargument name="mask" required="yes" type="string" default="yyyy-mm-dd">
<!--- Apply default date mask --->
<cfset var newDate = dateFormat(arguments.dateVal, arguments.mask)>
<!--- Apply custom date mask --->
<cfloop from="1" to="#arrayLen(arguments)-2#" index="loopIndex">
<cfset var maskPos = find("$#loopIndex#", newDate) - 1>
<cfswitch expression="#arguments[loopIndex+2]#">
<cfcase value="th">
<!--- Ordinal suffix mask --->
<cfif maskPos eq 1>
<!--- If mask is at first position of the string then replace it with blank --->
<cfset newDate = replace(newDate, "$#loopIndex#", "", "all")>
<cfelse>
<!--- Get last look behind number before maskPos location --->
<cfset lookBehind1Num = midLeft(newDate, maskPos, 1)>
<!--- Get second last look behind number before maskPos location --->
<cfset var lookBehind2Num = midLeft(newDate, maskPos-1, 1)>
<cfif lookBehind2Num eq 1>
<cfset newDate = replace(newDate, "$#loopIndex#", "th", "all")>
<cfelse>
<cfswitch expression="#lookBehind1Num#">
<cfcase value="1">
<cfset newDate = replace(newDate, "$#loopIndex#", "st", "all")>
</cfcase>
<cfcase value="2">
<cfset newDate = replace(newDate, "$#loopIndex#", "nd", "all")>
</cfcase>
<cfcase value="3">
<cfset newDate = replace(newDate, "$#loopIndex#", "rd", "all")>
</cfcase>
<cfdefaultcase>
<cfset newDate = replace(newDate, "$#loopIndex#", "th", "all")>
</cfdefaultcase>
</cfswitch>
</cfif>
</cfif>
</cfcase>
<cfdefaultcase>
<!--- Replace unknown custom masks with blank --->
<cfset newDate = replace(newDate, "$#loopIndex#", arguments[loopIndex+2], "all")>
</cfdefaultcase>
</cfswitch>
</cfloop>
<cfreturn newDate>
</cffunction>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment