Introduction
In this lab, we will explore how to use the Date object in JavaScript to find the last date of a given month. We will learn how to extract the year and month from a date, create a new date object with the last day of the previous month, and format the result as a string representation of the date. This lab will help you develop your understanding of the JavaScript Date object and its properties.
Function to Return the Last Date of a Month
To get started with coding, open the Terminal/SSH and type node.
This function returns the last date of the month for the given date.
To achieve this, follow these steps:
- Use
Date.prototype.getFullYear()andDate.prototype.getMonth()to get the current year and month from the given date. - Create a new date with the given year and month incremented by
1, and the day set to0(last day of previous month). You can use theDateconstructor for this purpose. - If no argument is passed to the function, it will use the current date by default.
- Return the last date of the month in the format of a string representation of the date.
Here is the code for the function:
const getLastDateOfMonth = (date = new Date()) => {
let lastDate = new Date(date.getFullYear(), date.getMonth() + 1, 0);
return lastDate.toISOString().split("T")[0];
};
You can test the function by calling it with a date object like this:
getLastDateOfMonth(new Date("2015-08-11")); // '2015-08-30'
Summary
Congratulations! You have completed the Last Date of Month lab. You can practice more labs in LabEx to improve your skills.