Skip to content

Instantly share code, notes, and snippets.

@JamoCA
Last active September 6, 2022 23:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JamoCA/8961085 to your computer and use it in GitHub Desktop.
Save JamoCA/8961085 to your computer and use it in GitHub Desktop.
ColdFusion UDF to format a date/time value to string format "yyyymmddHHmmssll" and back again. #dateHash(Now())# #dateUnHash("20140704")#
<cfscript>
/* 1/24/2011 james Moberg james@ssmedia.com
@param numberofChars, number of characters (Optional, 12 = default)
@param d, date/time string or object (Optional, now() = default)
@return Returns a yyyyMMddHHmmssll string (depending on length of numberofChars.)
Updated 20220903 to support millisecond */
string function dateHash(numeric numberofChars=12, date=now()) hint="I convert a date object to yyyymmddHHmmssll" {
var response = '';
if(not isvalid("date", arguments.date)) {
arguments.date = now();
}
response = "#dateFormat(arguments.date,'yyyymmdd')##timeFormat(arguments.date, 'HHmmssll')#";
if (arguments.numberofChars gt len(response)) arguments.numberofChars = len(response);
return left(response, arguments.numberofChars);
}
/* 9/21/2011 james Moberg james@ssmedia.com
@param i, hashed date yyyyMMddHHmmss
@return Returns a date/time object or an empty string
Updated 20220903 to support millisecond */
function dateUnHash(string input="") hint="I return a date based on yyyymmddHHmmssll string" {
var newDate = ""; var y=0; var m=0; var d=0; var h=0; var n=0; var s=0; var l=0;
var i = trim(arguments.input);
if (not isnumeric(i)) {i="";}
if (len(i) gte 4) {y = left(i,4);}
if (len(i) gte 6) {m = mid(i,5,2);}
if (len(i) gte 8) {d = mid(i,7,2);}
if (len(i) gte 10) {h = mid(i,9,2);}
if (len(i) gte 12) {n = mid(i,11,2);}
if (len(i) gte 14) {s = mid(i,13,2);}
if (len(i) gte 16) {l = mid(i,15,2);}
try {
switch(len(i)) {
case 4: newDate = createdate(y, 1, 1); break;
case 6: newDate = createdate(y, m, 1); break;
case 8: newDate = createdate(y, m, d); break;
case 10: newDate = createdatetime(y, m, d, h, 0, 0); break;
case 12: newDate = createdatetime(y, m, d, h, n, 0); break;
case 14: newDate = createdatetime(y, m, d, h, n, s); break;
case 16: newDate = createdatetime(y, m, d, h, n, s); newDate = dateadd("l", l, newDate); break;
}
} catch (any e) {
newDate = "";
}
return newDate;
}
</cfscript>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment