Sometimes, we want to get list of days in a month with JavaScript.
In this article, we’ll look at how to get list of days in a month with JavaScript.
How to get list of days in a month with JavaScript?
To get list of days in a month with JavaScript, we can use the Date
constructor and a while
loop.
For instance, we write:
const getDaysArray = (year, month) => {
const monthIndex = month - 1;
const names = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
const date = new Date(year, monthIndex, 1);
const result = [];
while (date.getMonth() === monthIndex) {
result.push(date.getDate() + '-' + names[date.getDay()]);
date.setDate(date.getDate() + 1);
}
return result;
}
console.log(getDaysArray(2020, 5))
We create the getDaysArray
function that takes the year
and month
as parameters.
Then we subtract month
by 1 and assign that to monthIndex
to make sure the months are between 0 and 11 as required by the Date
constructor.
Next, we create the names
array with the days of the week.
And then we create the first date
with the Date
constructor.
We then create the result
array to store the results.
Next, we create a while
loop to check if date.getMonth
returns the same value as monthIndex
.
If it’s not then date
is a date in the next month, so we end the loop.
In the loop body, we call result.push
to push the result into the result
array.
And the we call date.setDate
to change date
to the next day.
Finally, we return the results
.
Therefore, we get:
['1-fri', '2-sat', '3-sun', '4-mon', '5-tue', '6-wed', '7-thu', '8-fri', '9-sat', '10-sun', '11-mon', '12-tue', '13-wed', '14-thu', '15-fri', '16-sat', '17-sun', '18-mon', '19-tue', '20-wed', '21-thu', '22-fri', '23-sat', '24-sun', '25-mon', '26-tue', '27-wed', '28-thu', '29-fri', '30-sat', '31-sun']
from the console log.
Conclusion
To get list of days in a month with JavaScript, we can use the Date
constructor and a while
loop.