Number of Days in Month

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will delve into a JavaScript programming exercise that aims to determine the number of days in a given month of a specified year. Through this lab, you will learn how to use the Date constructor and the getDate() method to calculate the number of days in a month. You will also get a chance to practice your JavaScript skills and gain a better understanding of how date calculations work in JavaScript.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") subgraph Lab Skills javascript/variables -.-> lab-28255{{"`Number of Days in Month`"}} javascript/data_types -.-> lab-28255{{"`Number of Days in Month`"}} javascript/arith_ops -.-> lab-28255{{"`Number of Days in Month`"}} javascript/comp_ops -.-> lab-28255{{"`Number of Days in Month`"}} end

JavaScript Function to Get Number of Days in a Month

To find the number of days in a specific month of a given year using JavaScript, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Create a function named daysInMonth that takes two parameters: year and month.
  3. Inside the daysInMonth function, use the Date constructor to create a date object from the given year and month.
  4. Set the days parameter to 0 to get the last day of the previous month, since months are zero-indexed.
  5. Use Date.prototype.getDate() to return the number of days in the given month.
  6. Return the number of days from the daysInMonth function.

Here's the JavaScript code for the daysInMonth function:

const daysInMonth = (year, month) => new Date(year, month, 0).getDate();

You can use the daysInMonth function to get the number of days in any month of any year, as shown in these examples:

daysInMonth(2020, 12); // 31
daysInMonth(2024, 2); // 29

Summary

Congratulations! You have completed the Number of Days in Month lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like