Last Date of Month

JavaScriptJavaScriptBeginner
Practice Now

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

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.


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-28464{{"`Last Date of Month`"}} javascript/data_types -.-> lab-28464{{"`Last Date of Month`"}} javascript/arith_ops -.-> lab-28464{{"`Last Date of Month`"}} javascript/comp_ops -.-> lab-28464{{"`Last Date of Month`"}} end

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:

  1. Use Date.prototype.getFullYear() and Date.prototype.getMonth() to get the current year and month from the given date.
  2. Create a new date with the given year and month incremented by 1, and the day set to 0 (last day of previous month). You can use the Date constructor for this purpose.
  3. If no argument is passed to the function, it will use the current date by default.
  4. 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.

Other JavaScript Tutorials you may like