Get the number of days in a month using JavaScript

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 add 1 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.

Related Posts

How to Capture Screenshots with Puppeteer In NodeJS

How to Capture Screenshots with Puppeteer In NodeJS

To Capture Screenshots with Puppeteer: Launch a Browser Instance Navigate to the Web Page Capture the Screenshot Introduction: Puppeteer is a powerful Node.js library that allows developers…

How to Minimize Puppeteer Browser Window To Tray

How to Minimize Puppeteer Browser Window To Tray

Puppeteer is a powerful tool for automating tasks in headless or non-headless web browsers using JavaScript. While Puppeteer is often used to perform actions within a browser,…

Intercepting Responses in Node.js with Puppeteer

Intercepting Responses in Node.js with Puppeteer

Introduction: Puppeteer is a powerful Node.js library that provides a high-level API for controlling headless Chrome or Chromium browsers. It’s widely used for web scraping, automated testing,…

Mastering React Component Re-rendering in Jest

Mastering React Component Re-rendering in Jest

In this hands-on guide, we’ll explore the art of optimizing React component re-rendering within Jest tests. By combining theory with practical coding examples, you’ll gain a deep…

Eliminating Nesting Loops in React Rendering

Eliminating Nesting Loops in React Rendering

React has ushered in a new era of web application development with its component-based structure, promoting code reusability and maintainability. But as projects evolve, achieving optimal performance…

Exploring Type and Interface Usage in TypeScript

Exploring Type and Interface Usage in TypeScript

TypeScript has gained immense popularity by bridging the gap between dynamic JavaScript and static typing. Two of its fundamental features, “Type” and “Interface,” play pivotal roles in…

Leave a Reply

%d bloggers like this: