How to Get the First and Last Day of a Month in JavaScript

08/03/2021

Contents

In this article, you will learn how to get the first and last day of a month in JavaScript.

Getting the first and last day of a month in JavaScript

In JavaScript, we can get the first and last day of a month using the Date object and some simple arithmetic. Here’s how to do it in about 2000 characters:

Getting the first day of a month

To get the first day of a month, we need to create a new Date object and set the date to 1. Here’s an example:

function getFirstDayOfMonth(year, month) {
  return new Date(year, month, 1);
}

In this example, the getFirstDayOfMonth function takes two arguments: the year and the month (where January is 0, February is 1, and so on). We create a new Date object with the year, month, and 1 as arguments. This sets the date to the first day of the specified month.

We can then use various methods of the Date object to get information about the first day of the month. For example, we can use the getFullYear(), getMonth(), and getDate() methods to get the year, month, and day of the month, respectively. Here’s an example:

const firstDay = getFirstDayOfMonth(2023, 2);
console.log(`The first day of March 2023 is ${firstDay.toDateString()}.`);
// Output: The first day of March 2023 is Wed Mar 01 2023.

In this example, we call the getFirstDayOfMonth function with the arguments 2023 and 2, which represent March 2023. We then log the result to the console using the toDateString() method of the Date object, which returns a string representation of the date.

Getting the last day of a month

To get the last day of a month, we need to create a new Date object for the first day of the next month, and subtract one day from it. Here’s an example:

function getLastDayOfMonth(year, month) {
  return new Date(year, month + 1, 0);
}

In this example, the getLastDayOfMonth function takes the same arguments as getFirstDayOfMonth: the year and the month. We create a new Date object with the year, month + 1, and 0 as arguments. This sets the date to the first day of the next month, and subtracts one day to get the last day of the specified month.

We can then use the same methods of the Date object as before to get information about the last day of the month. Here’s an example:

const lastDay = getLastDayOfMonth(2023, 2);
console.log(`The last day of March 2023 is ${lastDay.toDateString()}.`);
// Output: The last day of March 2023 is Fri Mar 31 2023.

In this example, we call the getLastDayOfMonth function with the arguments 2023 and 2, which represent March 2023. We then log the result to the console using the toDateString() method of the Date object, which returns a string representation of the date.