YUI Calendar Changes Dates

October 21, 2008

My Ajax app has a persistent date it keeps track of, to compare other dates against. But I ran into a problem where the date was somehow being changed – from 12am on a certain day to 12pm. I looked through my code, and I wasn’t even changing it anywhere.

Finally, I noticed I was passing the date into a YUI Calendar object, to specify what was the minimum allowable selectable date. JavaScript Date objects are mutable, so I realized it was possible YUI was changing the hour value on the date. Sure enough, when I changed the code to pass YUI a copy of the Date instead, the date’s hour was no longer changed.

I’m still not entirely sure why YUI would need to change the Date, or if it’s even good design for it to do so instead of creating a copy of the Date object. Nonetheless, lesson learned: if you want to make sure an object you’re passing somewhere is unchanged, make a copy before you pass it. This smacks of a general OO principle, but for some reason I haven’t run across this problem in the Java world before.