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

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. Similarly, to get the last day of the month, we need to pass the parameter 0 instead of 1.

Using a Date Object

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. Remember that the Months are from 0(January) to 11(December).

Using a Moment.js library

You can install the Moment.js library using this command:

npm install moment --save

To get the first and last date of the current month using Moment.js, you can follow the steps below:

  1. First, make sure you have included the Moment.js library in your project. If you haven’t, you can include it using a CDN or install it via npm, depending on your project setup.
  2. To get the first date of the current month:
const moment = require('moment');

const firstDateOfMonth = moment().startOf('month').format('YYYY-MM-DD');
console.log(firstDateOfMonth);

const lastDateOfMonth = moment().endOf('month').format('YYYY-MM-DD');
console.log(lastDateOfMonth);

Output

2023-08-01
2023-08-31

That’s it!

Leave a Comment