Introduction
There are a few options we can use to get the number of days in a month using JavaScript, let’s check the following examples to see how we can get them.
Option 1: Using the Date constructor
We can instantiate a new date using `new Date()`
, then pass the year
, month
, and 0 for the days
parameter, then call the getDate
method, then we will be able to get the number of days for any specific month.
Example
To get the days in September 2022, we can apply the following:
1- Instantiate a `new Date()`
object.
2- Pass the year
, month
, and 0 for days
.
3- Call the getDate
method on the new instance, then you will get the number of days in that month.
console.log(new Date(2022, 9, 0).getDate())
// Output: 30
Extending the above example into more re-usable functionality:
const getDaysInAmonth = (year, month) => {
return new Date(year, month, 0).getDate();
};
console.log('Days in Sept:', getDaysInAmonth(2022, 9));
// Days in Sept: 30
console.log('Days in May:', getDaysInAmonth(2022, 5));
// Days in May: 31
console.log('Days in Feb:', getDaysInAmonth(2022, 2));
// Days in Feb: 28
Another example using date value as a string
const getDaysInAmonth = (year, month) => {
return new Date(year, month, 0).getDate();
};
const dateAsString = new Date("2022-09-29");
console.log("Days in Sept:", getDaysInAmonth(dateAsString.getYear(), dateAsString.getMonth() + 1))
// Output:
// Days in Sept: 30
Note: months in Javascript are zero indexed, meaning the months count start from 0 for January, till 11 for December. That’s why we have added +1 to the
getMonth
method, to return Days in September, if we haven’t added+1
, days in Augest will be returned.So If you’re passing the result of calling
getMonth
to the function, make sure to add1
to the month index.
Option 2: Using the Date-fns getDaysInMonth method
Date-fns has already a built-in method (getDaysInMonth
) that we can use to get the number of days in a specific month.
Example:
import getDaysInMonth from "date-fns/get_days_in_month";
// Note the month index, Sept=8
console.log("Days in Sept:", getDaysInMonth(new Date(2022, 8)));
// Output: Days in Sept: 30
console.log("Days in Oct:", getDaysInMonth(new Date(2022, 9)));
// Output: Days in Oct: 31
console.log("Days in Aug:", getDaysInMonth(new Date(2022, 7)));
// Output: Days in Aug: 31
const dateAsString = new Date("2022-09-29");
console.log("Days in Sept:", getDaysInMonth(dateAsString));
// Output: Days in Aug: 31
Note, using date-fns functionality, we’ve passed the month index, not the month number as in the examples in the first option. In this case date-fns internally will handle getting the correct month days for us.
That’s it for how to get the number of days in a month using JavaScript.
Photo from unslpash.