UDF: Convert ColdFusion Date to JavaScript Date Object

Posted by Dan on May 2, 2008 @ 1:43 PM

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:

function jsDateFormat(date){
    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:

<script type="text/javascript">
var today = <cfoutput>#jsDateFormat(now())#</cfoutput>;

This would then generate the following:

<script type="text/javascript">
var today = new Date(2008, 4, 2, 13, 32, 16);

Obviously this is pretty straightforward, but it's saved me a lot of repetitive typing today and simplified the readability of my code.

Categories: HTML/ColdFusion, Source Code


Add Comment

Leave this field empty