Reputation: 30342
I've created the following function that should return the number of days in a month but I'm not getting expected results.
export const getNumberOfDaysInMonth = (year, month) => {
const myDate = new Date(year, month - 1, 0);
return myDate.getDate();
}
I'm passing year = 2017
and month = 6
. As you'll see I'm subtracting 1 from month because as I understand it, JS uses a 0 based numbering system for months.
This sets myDate to May 31, 2017 and the function returns 31 days.
If I change the formula to const myDate = new Date(year, month - 1, 1);
, it does set the date to June 1, 2017 and returns 1 day as the number of days.
I can use a switch statement to return the number of days in a month but that seems cumbersome and it wouldn't even take into account leap years, etc. Is there an elegant way to get the total number of days in a particular month in a particular year?
For example, if I pass year = 2016
and month = 2
, I should get 29 not 28.
Upvotes: 1
Views: 65
Reputation: 9310
When doing
const myDate = new Date(year, month - 1, 0);
you don't need to subtract 1
from the month. This is because the third parameter in the date function here, represents the day
of the month, is set to 0
which actually means last day of the previous month. So just doing this
const myDate = new Date(year, month, 0);
should give you the desired result of number of days in a month.
Upvotes: 1