UDF: Convert ColdFusion Date to JavaScript Date Object
I had the need to convert a ColdFusion date/time stamp to a JS Date Object. I thought serializeJSON() function would handle this, but it turns out it treats CF date/time variables as strings. The toScript() function will convert CF variables to JS Date Objects—provided that the date/time variable is in ODBC format (i.e. {ts '2008-05-02 13:32:16'}.)
However, I wanted something that would work for anything that ColdFusion saw as a Date object, so I just whipped out this little 4 line helper function:
if( isDate(date)) return 'new Date(#year(date)#, #(month(date)-1)#, #day(date)#, #hour(date)#, #minute(date)#, #second(date)#)';
else return "null";
}
If ColdFusion doesn't see the date as a date object, then it'll set the date/time to "null". To use this function you just do:
var today = <cfoutput>#jsDateFormat(now())#</cfoutput>;
</script>
This would then generate the following:
var today = new Date(2008, 4, 2, 13, 32, 16);
</script>
Obviously this is pretty straightforward, but it's saved me a lot of repetitive typing today and simplified the readability of my code.
Comments
In the Date Object in JavaScript, the month ranges from 0-11, so you need to subtract 1 from the CF date (since it's from 1-12.) Trust me, the code is correct.
The odds are you're wanting to do more than just data object to CF, but you can certainly use AJAX to send the date object to CF.
Serialize using JSON.
Just use a JSON helper library. It'll manage the conversion of the JS objects and convert them to the correct JSON string.
See http://www.json.org/ for more information. (In newer versions of CF, there's native support for deserializing JSON using deserializeJSON().)
