Open In App

How to to Get Number of Days in Current Month in Moment.JS?

Last Updated : 20 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

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.

JavaScript
// 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:

daysInMoment
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

JavaScript
// 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:

moment-method
Output

Next Article

Similar Reads