While working with dates in JavaScript, sometimes we need to find the number of days in the current month. For example, February has 28 or 29 days depending on whether it's a leap year or not, while other months have 30 or 31 days. Moment.js is a powerful JavaScript library that makes handling dates and times easier.
Below are different approaches to finding out the number of days in the current month using Moment.js:
Table of Content
Using the dayInMonths() method
Moment.js provides an easy method called daysInMonth(), which returns the number of days in the month for a given date. This is the most straightforward way to find the number of days in the current month.
Example: This example shows the use of dayInMonths() method.
// Import Moment.js
const moment = require('moment');
// Get the number of days in the current month
let daysInCurrentMonth = moment().daysInMonth();
console.log(`Number of days in the current month: ${daysInCurrentMonth}`);
Output:

Using endOf('month').date() Method
In this method, we use a a few different methods available in Moment.js to calculate the number of days in the current month. This approach is more manual, but it can be useful if we need to understand how dates work.
Syntax:
moment().endOf('month').date();Example: Below is example Code of above method
// Import Moment.js
const moment = require('moment');
// Get the number of days in the current month
// by finding the last day of the month
let lastDayOfMonth = moment().endOf('month').date();
console.log(`Number of days in the
current month: ${lastDayOfMonth}`);
Output:
