The problem was started just a few weeks ago.
var test = new Date()
test.setDate(31)
test.setMonth(4) = May
test.setFullYear(2019)
test.setHours(0,0,0,0)
console.log(test.toLocaleDateString())
I get 5/1/2019 instead of 5/31/2019
What’s wrong?
The problem was started just a few weeks ago.
var test = new Date()
test.setDate(31)
test.setMonth(4) = May
test.setFullYear(2019)
test.setHours(0,0,0,0)
console.log(test.toLocaleDateString())
I get 5/1/2019 instead of 5/31/2019
What’s wrong?
Be careful when you try to use setMonth to set a month on May 31 or any 31st of the year…
var my_date = new Date();
my_date.setMonth(1);
…as it leads to strange behavior because (1) (February) only has 28 days leading to set the Month to March (3). The same with (3) (April), (5) (June), (8) (September) and (10) (November) with all having 30 days leading to set the Month to (4) May, (6) July, (9) October and (11) December respectively.
Have a read of these links, with the top link having other links that you can go and view if you wish:
Date.prototype.toLocaleString() - JavaScript | MDN
Understanding Date and Time in JavaScript | DigitalOcean
You need to set the month before setting the day or use the Date(yearval, monthval, dayval) constructor), so do d = new Date(yearval, monthval, dayval) instead of doing the seperate .set…() calls. Do it in a single call gets around these wrapping issues.
When you create a Date object, it defaults to the current date, so say the time of writing is June and only having 30 days, so when you try to set the day to 31 it wraps. …And because of similar behaviour in leap years, you should set the year before setting the month or day.
Right hierarchy is set year, then Month and at last add the Day. This will return the exact date that you added.
//Wrong order- will return 1 May 2019
var start = new Date();
start.setDate(31);
start.setMonth(4);
start.setFullYear(2019);
//Right order - will return 31 May 2019
var end = new Date();
end.setFullYear(2019);
end.setMonth(4);
end.setDate(31);
Got it. thanks