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.
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:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Create a function named
daysInMonththat takes two parameters:yearandmonth. - Inside the
daysInMonthfunction, use theDateconstructor to create a date object from the givenyearandmonth. - Set the days parameter to
0to get the last day of the previous month, since months are zero-indexed. - Use
Date.prototype.getDate()to return the number of days in the givenmonth. - Return the number of days from the
daysInMonthfunction.
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.