A long time ago, Jack needed a function to return a JavaScript date object which represented New Year’s Day for any year which he specified, or for the current year if none was provided.
This is what he came up with:
function getNewYearsDate(yr){
var nyDate = new Date("");
if ( typeof yr === "undefined"){
var tmpDate = new Date();
yr = tmpDate.getFullYear();
}
nyDate.setMonth(0);
nyDate.setDate(1);
nyDate.setYear(yr);
return nyDate;
}
Of course, Jack tested his function carefully . . .
getNewYearsDate(2020);
// returns Wed Jan 01 2020 00:00:00 GMT-0500 (Eastern Standard Time)
getNewYearsDate();
// returns Tue Jan 01 2019 00:00:00 GMT-0500 (Eastern Standard Time)
and seeing the results he expected to see, Jack pushed this change to production where it worked wonderfully for many months.
This morning, Jack identified a need for a similar function which represents July 4th/Independence Day. Because Jack is in a rush, he decides to copy and alter his getNewYearsDate function to handle returning the date for Independence Day in the United States (July 4th).
Here’s what he did:
function getIndependenceDate(yr){
var idDate = new Date("");
if ( typeof yr === "undefined"){
var tmpDate = new Date();
yr = tmpDate.getFullYear();
}
idDate.setMonth(6);
idDate.setDate(4);
idDate.setYear(yr);
return idDate;
}
But this time, when he tests his new function, he gets surprising results!
getIndependenceDate()
Tue Jan 01 2019 00:00:00 GMT-0500 (Eastern Standard Time)
getIndependenceDate(2020)
Wed Jan 01 2020 00:00:00 GMT-0500 (Eastern Standard Time)
Can you see why the getNewYearsDate() function works, while the getIndependenceDate() function fails?
If so, how would you alter the getIndependenceDate() function so it returns the correct value?