Skip to content

JavaScript get last day of month

  • by

You can use JavaScript’s built-in Date object to get the last day of a month. Create a new date object for the first day of the next month and set the day to 0 (which means the last day of the previous month).

JavaScript gets the last day of the month example

Simple example code.

<!DOCTYPE html>
<html>
<body>
    <script>
        var month = 0; // January
        var d = new Date(2008, month + 1, 0);
        console.log(d.toString());

    </script>
</body>
</html>

Output:

JavaScript get last day of month

JavaScript gets the last day of the Month – based on Year, Month, and day

function getLastDayOfMonth(date) {
  // Get the year and month from the given date object
  const year = date.getFullYear();
  const month = date.getMonth();

  // Create a new date object for the next month
  // and set its day to 0, which means the last day of the current month
  const lastDayOfMonth = new Date(year, month + 1, 0);

  // Return the last day of the month
  return lastDayOfMonth.getDate();
}
const myDate = new Date('2023-04-15');
console.log(getLastDayOfMonth(myDate));

Output: 30

Do comment if you have any doubts or suggestions on this Js date object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Tags:

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading