UDF: Convert ColdFusion Date to JavaScript Date Object

Categories: HTML/ColdFusion, Source Code

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>;
</script>

This would then generate the following:

<script type="text/javascript">
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

shag's Gravatar this is pretty cool. im not sure most people would want to subtract a month from the date. i'm pretty sure that would cause problems for january as well. not to mention you exclude december. very cool tool though.
Dan G. Switzer, II's Gravatar @Shag:

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.
shag's Gravatar i guess thats what i get for having avoided javascript for all these years.

Add Comment



If you subscribe, any new posts to this thread will be sent to your email address.