The Wayback Machine - https://web.archive.org/web/20241009135109/https://www.geeksforgeeks.org/how-to-get-the-number-of-days-in-a-specified-month-using-javascript/
Open In App

How to get the number of days in a specified month using JavaScript ?

Last Updated : 15 May, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a month the task is to determine the number of days of that month using JavaScript. we can use the getDate() method for the calculation of number of days in a month.

JavaScript getDate() Method

getDate() method returns the number of days in a month (from 1 to 31) for the defined date. 

Syntax:

Date.getDate();

Return value:

It returns a number, from 1 to 31, representing the day of the month.

Example 1: This example gets the days in the month (February) of the year (2020) by passing the month (1-12) and year to the function daysInMonth. 

JavaScript
function daysInMonth(month, year) {
    return new Date(year, month, 0).getDate();
}

function GFG_Fun() {
    let date = new Date();
    let month = 2;
    let year = 2020;
    console.log("Number of days in " + month
        + "and month of the year " + year
        + " is " + daysInMonth(month, year));
}
GFG_Fun()

Output
Number of days in 2and month of the year 2020 is 29

Example 2: This example gets the days in the current month of the current year by passing the month (1-12) and year to the function daysInMonth. 

JavaScript
function daysInMonth(month, year) {
    return new Date(year, month, 0).getDate();
}

function GFG_Fun() {
    let date = new Date();
    let month = date.getMonth() + 1;
    let year = date.getFullYear();
    console.log("Number of days in " + month
        + "th month of the year " + year
        + " is " + daysInMonth(month, year));
}
GFG_Fun()

Output
Number of days in 5th month of the year 2024 is 31

2. Using an array to store days in each month

Example 1: Using an array to store days in each month allows for efficient retrieval of the number of days in a specific month based on its index.

JavaScript
function daysInMonth(month, year) {
    const daysInMonths = [31, (year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    return daysInMonths[month - 1];
}

// Example usage:
let month = 2;
let year = 2024;
console.log("Number of days in " + month + "th month of the year " + year + " is " + daysInMonth(month, year));

Output
Number of days in 2th month of the year 2024 is 29


3. Using switch statement

In this approach, a switch statement is used to return the number of days based on the specified month. This approach is straightforward and allows for direct mapping of month numbers to the corresponding number of days.

JavaScript
function daysInMonth(month, year) {
    switch (month) {
        case 1: // January
        case 3: // March
        case 5: // May
        case 7: // July
        case 8: // August
        case 10: // October
        case 12: // December
            return 31;
        case 4: // April
        case 6: // June
        case 9: // September
        case 11: // November
            return 30;
        case 2: // February
            return (year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)) ? 29 : 28;
        default:
            return -1; // Invalid month
    }
}

// Example usage:
let month = 2;
let year = 2024;
console.log("Number of days in " + month + "th month of the year " + year + " is " + daysInMonth(month, year));

Output
Number of days in 2th month of the year 2024 is 29


We have a complete list of Javascript Date Objects, to check those please go through this Javascript Date Object Complete reference article.



Previous Article
Next Article

Similar Reads

How to Get Number of Days in Current Month in PHP?
This article will show you how to get the number of days in the current month in PHP. In PHP, you may need to find the number of days in the current month for various purposes, such as generating a calendar or performing date calculations. There are three approaches to get the number of days in the current month, these are described below: Table of
3 min read
How to to Get Number of Days in Current Month in Moment.JS?
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
2 min read
How to get the number of occurrences of each letter in specified string in JavaScript ?
In this article, we are given a string, our task is to find the occurrence of a character in the string with the help of a user-defined function. Example:Input : "hello"Output : h occur 1 times e occur 1 times l occur 2 times o occur 1 timesExplanation : here "hello" have 1 h, so it have 1 value. as same e have 1, l have 2 , o have 1.Example 2:Inpu
5 min read
How to get the day and month of a year using JavaScript ?
Given a date and the task is to get the day and month of a year using JavaScript. Approach: First get the current date by using new Date().Use getDay() method to get the current day in number format, Map it to the day name.Use getMonth() to get the current month in number format, Map it to the month name. Example 1: In this example, the month and d
2 min read
How to get the first and last date of current month using JavaScript ?
Given a month and the task is to determine the first and last day of that month in proper format using JavaScript. JavaScript getDate() Method: This method returns the day of the month (from 1 to 31) for the defined date. Syntax: Date.getDate() Parameters: This method does not accept any parameters. Return value: It returns a number from 1 to 31, r
3 min read
How to get the month name from Date using JavaScript ?
The purpose of this article is to get the month name from a particular date using JavaScript getMonth() method. This method is used to fetch the month(0 to 11) from the given Date object. It returns an integer value ranging from (0 to 11) Zero (0) means January, 1 means February, and so on, till 11 means December. Syntax: DateObj.getMonth() Example
1 min read
How to get Day Month and Year from Date Object in JavaScript ?
We have given the Date object and the task is to extract the Day, Month, and Year from the Date object and print it using JavaScript. Below is an example for better understanding. Example:Input: Date ObjectOutput: Day: 26 Month: 11 Year: 2023To extract Day, Month, and Year from Date Object, we have three different methods which are stated below: Ta
3 min read
How to get Month and Date of JavaScript in two digit format ?
To get the Month and Date of JavaScript in two-digit format, we have multiple approaches. In this article, we are going to learn how to get the Month and Date of JavaScript in a two-digit format. Below are the approaches used to get the Month and Date of JavaScript in two-digit format: Table of Content Approach 1: Using padStart() methodApproach 2:
3 min read
How to get/set elements containing the closest parent element matches the specified selector using jQuery ?
In this article, we will learn how to get a set of elements containing the closest parent element that matches the specified selector, the starting element included using jQuery. JQuery is the fastest and lightweight JavaScript library that is used to simplify the interactions between an HTML/CSS document, or more precisely the Document Object Mode
2 min read
How to get Difference between two Dates in days using jQuery ?
In this article, we will learn how to find the difference between the 2 dates in days using jQuery. Here, we will take the input for the dates using a jquery datepicker. Considering the given below 2 input Dates, we need to calculate the difference between them which will be returned in a number of days. Input : 02/17/2022 02/10/2022Output: 7For th
3 min read
How to Get Last Day of Previous Month From Date in Moment.JS?
To get the last day of the previous month from a given date in Moment.js, you need to adjust the date to the start of the current month and then subtract one day. This approach allows you to accurately find the final day of the previous month regardless of varying month lengths. Installing Moment.js in Node.jsWe have to first install moment.js usin
2 min read
How to move specified number of elements to the end of an array in JavaScript ?
The purpose of this article is to move some specified elements to the end of an array using JavaScript. Given an array of length say N, move some specified amount of elements say X to the end of the given array. Input: arr = [1, 2, 3, 4, 5]X = 2Output: The following array should be the output as the first two numbers are moved to the end of the arr
3 min read
How to implement a function that enable another function after specified time using JavaScript ?
Let us assume that we have been given a function add() which takes in two parameters a and b, and returns their sum. We are supposed to implement a function that should be able to call any function after the given delay amount of time. This can be done with the approaches as given below: Approach 1: Create a function that takes in the amount of del
2 min read
Write a program to convert an array of objects to a CSV string that contains only the columns specified using JavaScript
When we want to store multiple values in one variable then instead of a variable, we use an array. which allows you to store multiple types of data for example you could have a string, an integer, etc. In this article, we will learn to convert the array objects to CSV string data. Given array objects ( key: value ) to CSV string comma-separated val
3 min read
How to Calculate the Number of Days between Two Dates in JavaScript?
Given two Dates and the task is to get the number of days between two dates in JavaScript. To calculate the number of days between two dates in JavaScript, we use the Date object and subtract dates using milliseconds. Below are the methods commonly used to determine the number of days between two dates: Table of Content Using Two different dates Us
5 min read
How to calculate days left until next Christmas using JavaScript ?
In this article, we will learn how to calculate the number of days left until next Christmas using JavaScript. Christmas marks the birth of Christ, mainly celebrated by millions of people around the globe on 25 December every year as a religious and cultural festival. Approach: In order to calculate the number of days between two dates in JavaScrip
3 min read
JavaScript: Check the Month is in Which Quarter?
When working with dates in JavaScript, it's often useful to determine which quarter a particular month falls into. Knowing the quarter can aid in various date-related calculations or visual representations. In this article, we will explore different approaches to check the month and it's quarter using JavaScript. These are the following approaches:
2 min read
How to replace characters except last with the specified mask character in JavaScript ?
In this article, we have given a number and the task is to replace the characters except for the last character with a specified mask character in JavaScript. These are the following methods: Using Naive approachUsing slice() and replace methodUsing reduce() methodExample: Let's take a number 12345678 and the masking character is * and the number o
4 min read
How to create a new object from the specified object, where all the keys are in lowercase in JavaScript?
In this article, we will learn how to make a new object from the specified object where all the keys are in lowercase using JavaScript. Example: Here, we have converted the upper case to lower case key values. Input: {RollNo : 1, Mark : 78} Output: {rollno : 1, mark : 78} Approach 1: A simple approach is to Extract keys from Object and LowerCase to
2 min read
How to check if the provided value is of the specified type in JavaScript ?
To check if the provided value is of the specified type in JavaScript, we have multiple approaches. Below are the approaches used to check if the provided value is of the specified type in JavaScript: Table of Content Using Object.is() Using TypeOf OperatorApproach: Using Object.is() Object.is() determines whether two values are the same value. Two
3 min read
How to Flatten a Given Array up to Specified Depth in JavaScript?
Flatten an array in JavaScript is a common task when dealing with nested arrays. The concept of "flatten" means to convert a multi-dimensional array into a single-dimensional array. When you need to control the depth of flattening, JavaScript provides methods to handle this efficiently. This process involves reducing the array’s depth up to a speci
2 min read
How to check the given element has the specified class in JavaScript ?
In JavaScript, checking if a given element has a specified class involves verifying whether the element includes a particular class name within its list of classes. This can be useful for applying conditional styling, behaviors, or logic based on the presence of specific CSS classes. Here we have two different approaches to check the given element
2 min read
JavaScript Adding days in milliseconds to Date object
Given a date, the task is to add days in milliseconds to it using JavaScript. To add days in milliseconds to date objects in JavaScript, some methods are used which are listed below: JavaScript getMilliseconds() Method: This method returns the milliseconds (from 0 to 999) of the provided date and time. Syntax: Date.getMilliseconds() Parameters: Thi
2 min read
JavaScript Subtract Days from Date Object
Given a date and the task is to subtract days from the date using JavaScript. To subtract days from date, some methods are used which are described below: JavaScript getDate() Method: This method returns the day of the month (from 1 to 31) for the defined date. Syntax: Date.getDate() Parameters: This method does not accept any parameters. Return va
3 min read
How to Add Days to Date in JavaScript?
Adding days to a date in JavaScript is a common task when working with dates and times. This involves manipulating the Date object to calculate a future or past date by adding a specific number of days. This is useful for tasks like scheduling events, and deadlines, or simply adjusting dates dynamically within an application. There are two methods
2 min read
How to create a Month Input using jQuery Mobile ?
jQuery Mobile is a web based technology used to make responsive content that can be accessed on all smartphones, tablets and desktops. In this article, we will be creating a Month Input area using jQuery Mobile. Approach: Add jQuery Mobile scripts needed for your project. <link rel=”stylesheet” href=”http://code.jquery.com/mobile/1.4.5/jquery.mo
1 min read
How to Subtract One Month using Moment.JS?
Sometimes we need to subtract a certain amount of time, like one month, from a given date. we are going to discuss how we can subtract one month from a date using MomentJS. Installing Moment.js in Node.jsWe have to first install moment.js using the following command in the terminal: npm install momentBelow is an approach on how to subtract one mont
2 min read
Web crawling using Breadth First Search at a specified depth
Web scraping is extensively being used in many industrial applications today. Be it in the field of natural language understanding or data analytics, scraping data from websites is one of the main aspects of many such applications. Scraping of data from websites is extracting large amount of contextual texts from a set of websites for different use
5 min read
How to make border around all unordered list items that are children of a specified class using jQuery ?
In this article, we will see how to set a border around all list items that are children of a specified class of an unordered list using jQuery. This task can be done by using the children selector() method. children selector("parent > child") - As you notice from the name itself that it takes two arguments and then perform the task. It selects
1 min read
How to find all children with a specified class using jQuery ?
There are lots of javascript libraries like - anime.js, screenfull.js, moment.js, etc. JQuery is also a part of javascript libraries. It is used to simplify the code. It is a lightweight and feature-rich library. In this article, we will learn how to find all children with a specified class of each division. .children(selector) - In jquery you can
2 min read