Working with ColdFusion Dates in Javascript
I did not see much information out there on this subject so I thought I would post it. Here is the scenario, you want to return a date from the server and use it in Javascript to dynamically populate something (an input field, some text... you decide.)
When you send a date back from the server using AJAXPROXY, or manually using SerializeJSON(), ColdFusion is extremely helpful and sends the date back in this format.
MonthName, DayNumber Year Hours:Minutes:Seconds
Now... what can you do with that format on the Javascript side? More than you may have realized.
All you need to do is put that date in the constructor of the Javascript Date object. Now you automagically have a Javascript Date object and can use all the methods for that (Check out the documentation on Javascript Date Objects.) Here is some code that you can run to see what I mean.
<script>
var myCfc = new myCfc();
var myDate = new Date(myCfc.getMyDate());
document.write(myDate.getMonth()+1 + '/' + myDate.getDate() + '/' + myDate.getFullYear());
</script>
The output will look like this.
01/01/2010
I know you're probably asking... why do you have to add 1 to the month. getMonth() returns the number of the month (0-11) starting at 0. Most of the methods start at 0, just add 1 when you need to. The exception to that rule is getDate() which returns the number of the day starting at 1. Also, getDay(), actually returns the day of the week. I find that a bit odd myself, but am sure that there were reasons to do it that way.
Don't forget, you have the time in the object as well. So you can use getHours(), getMinutes(), and getSeconds() to output the time... or you can use myDate.toLocaleTimeString() and javascript will output the time in the appropriate format for the users locale.
Hopefully that will save you a bit of extra time trying to figure out how to return a date from the server and format your date in Javascript.
Cheers! Jason
P.S. This is not an April fools joke. :)

There are no comments for this entry.
[Add Comment]