JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to get the first and last day of the current month in JavaScript?

If you want to find the first and last day of the current month:

  1. Start by creating a Date object by calling the Date() constructor with no arguments.
  2. Get the current month using the getMonth() method.
  3. Grab the current year by calling the getFullYear() method.
  4. In the end, create two Date objects.
  5. In the first Date object, specify 1 as the month's date. new Date(currentYear, currentMonth, 1)
  6. On the other hand, in the second Date object, set 0 as the date and month + 1 as the month argument. new Date(currentYear, currentMonth + 1, 0)
let d = new Date(),
    currentYear = d.getFullYear(),
    currentMonth = d.getMonth();

let firstDay = new Date(currentYear, currentMonth, 1);
let lastDay = new Date(currentYear, currentMonth + 1, 0);

console.log(firstDay.toString()); //Tue Feb 01 2022
console.log(lastDay.toString()); //Mon Feb 28 2022

You might notice why 0 is passed to the Date() object. The reason for this is that the Date class automatically adjusts the value of month and date based on the values passed to it. As 0 does not exist in the month, 0 will be changed to the previous month's last day, and the month is reduced by 1.

The best thing about the steps mentioned in this tutorial is that you don't have to remember whether the month has 28, 29, 30, or 31 days.

Recommended Posts