How to Get First and Last Day of Current Month in JavaScript

Many of the times the programmers need to access the first and the last date of the current month in javascript. Knowing how to do so is important because a lot of work on the web is done through the use of time.

In this article, we are going to learn how to get the first and last day of the current month in javascript.

How to Get First and Last Day of Current Month in JavaScript

  1. JavaScript offers a unique way to access the first and the last day of the month. To get the current year and month, you can use the getFullYear() and getMonth() methods and pass them to the date constructor. Year, month and pass a third parameter 1 to get the first date of the month.
  2. Similarly to get the last day of the month we need to pass the parameter 0 instead of 1.

Example

let date_today = new Date();

let firstDay = new Date(date_today.getFullYear(), date_today.getMonth(), 1);

console.log(`Current year is: ${date_today.getFullYear()}`);

console.log(`Index of current month is: ${date_today.getMonth()}`);

let lastDay = new Date(date_today.getFullYear(), date_today.getMonth() + 1, 0);

console.log(`The first date of the current month is: ${firstDay.toString()}`); 

console.log(`The last date of the current month is: ${lastDay.toString()}`); 

Output

Current year is: 2022

Index of current month is: 8

The first date of the current month is: Thu Sep 01 2022 00:00:00 GMT+0530 (India Standard Time)

The last date of the current month is: Fri Sep 30 2022 00:00:00 GMT+0530 (India Standard Time)

Explanation

The above code can be explained as follows

  1. We first created the variable named date_today using the let keyword and initialized it with the constructor new Date().    
  2. Then we created another variable named firstDay.As we passed the current year, index of the current month, and 1 to the constructor to obtain the first date of the month.
  3. Similarly to obtain the last date of the month we have created another variable named lastDay and passed the current year, index of current month+1 and 0 as the argument. We set the day to  ‘0’ indicates gives us the last day of the month. When we add 1 to the getMonth() method’s return value, we will move one month forward and then we go one day back by specifying 0 as the last day of the previous month.
  4. We have also printed the desired variables in the console.
  5. Keep in mind that the Months are from 0(January) to 11(December).

Conclusion

In this article, we have looked at how to get the first and the last date of the current month. Especially in web technology, and blockchain implementations these concepts are used frequently. Programmers, therefore, need to know about these concepts.

Leave a Comment