Ever had a problem with JavaScript’s setFullYear method in the Date object?
October 20, 2008 – 8:32 pm
Me too.
While writing a JavaScript countdown timer the other day I ran into a very peculiar issue. Every time I refreshed the page, the countdown had 0 hours, 59 minutes, and 59 seconds remaining, regardless of the current time, but it had the correct number of days.
To set the future date I used the setFullYear method of the JS Date object as such:
var futureDate = new Date();
futureDate.setFullYear(2009, 0, 1);
The above sets futureDate to January 1, 2009. The problem is that the hours, minutes, and seconds are not being set with that method. So what values do they inherit? They are populated with the hours, minutes, and seconds of the current time stamp. This doesn’t make any sense to me. In my humble opinion they should default to 0, 0, and 0 (respectively).
To remedy the issue I used the following code:
var futureDate = new Date();
futureDate.setFullYear(2009, 0, 1);
futureDate.setHours(0);
futureDate.setMinutes(0);
futureDate.setSeconds(0);
This is the same as the previous code except I am explicitly setting the hours, minutes, and seconds so they don’t inherit the current time stamp’s values.
Was this helpful? Check out these related posts: