To find all the days in a month with the JavaScript Date object, we can create an array with the all dates of the month in it.
To do this, we write:
const getDaysInMonth = (month, year) => {
return new Array(31)
.fill('')
.map((v, i) => new Date(year, month - 1, i + 1))
.filter(v => v.getMonth() === month - 1)
}
console.log(getDaysInMonth(2, 2020))
We create an array with 31 entries initally with new Array(31)
.
Then we call fill
to fill the empty slots with empty strings.
Next, w call map
to map each index, with the dates of the month with new Date(year, month — 1, i + 1)
.
JavaScript date months starts with 0 for January to 11 for December, so we’ve to subtract month
by 1.
And we’ve to add 1 to 1
to get all the days of the month.
If the day of the month exceeds, the max, the month will be incremented by 1.
So we can just call filter
to filter out all the dates with the month that’s 1 more than month — 1
to get the right dates for month
.
Therefore, the console log should have 29 days in it since February 2020 has 29 days.