Jenny Mok Jenny Mok - 1 month ago 7
Javascript Question

setDate doesn't return the last day of the month Javascript

I expect 31 because this month October has 31 days, which part of my code is wrong here?

function lastDayOfMonth(given_month) {
var d = new Date();
d.setDate(0);
d.setMonth(given_month);
return d.toISOString();
}

console.log(lastDayOfMonth(given_month))



2016-10-30T13:16:14.227Z

sb9 sb9
Answer
d.setDate(0);

sets the date to the last day of the previous month. I.e if you run this script in October, the date will be set to Sep 30.

Afterwards you run

d.setMonth(given_month);

This sets the month, but leaves the day of month as it is. I assume that given_month is 9 (i.e. Oct), so this will result in Oct 30.

See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date/setDate for more info.