Check if a Date is the First day of the Month in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jan 26, 2022

banner

Photo from Unsplash

Check if a Date is the First day of the Month in JavaScript #

To check if a date is the first day of the month:

  1. Use the getDate() method to get the day of the month for the given date.
  2. If the result is equal to 1, the date is the first day of the month.
index.js
function isFirstDayOfMonth(date = new Date()) { return date.getDate() === 1; } // 👇️ true console.log(isFirstDayOfMonth(new Date('2022-02-01'))); // 👇️ false console.log(isFirstDayOfMonth(new Date('2022-02-02')));

We created a reusable function that takes a Date object as a parameter and checks if the date is the first day of the month.

If the function is called without a parameter, it uses the current date.

The getDate() method returns a number between 1 and 31 that represents the day of the month for the given date.

If the getDate() method returns 1, then the date stores the first day of the given month.

To check if a date is the first day of the current month:

  1. Create a new Date object that stores the first day of the current month.
  2. Use the toDateString() method on both dates.
  3. If the method returns 2 equal strings, then the date is the first day of the current month.
index.js
function isFirstDayOfMonth(date = new Date()) { const firstDayCurrentMonth = new Date(); firstDayCurrentMonth.setDate(1); return firstDayCurrentMonth.toDateString() === date.toDateString(); } // 👇️ (Today is 26th of January 2022) console.log(isFirstDayOfMonth(new Date('2022-01-01'))); // 👉️ true console.log(isFirstDayOfMonth(new Date('2022-02-02'))); // 👉️ false

The first thing we did in the function is create a Date object that stores the date for the first day of the current month.

We created a Date object that stores the current date and set its day of the month value to 1.

The toDateString method returns the date portion of a Date object in human-readable form.

index.js
// 👇️ Wed Jan 26 2022 console.log(new Date().toDateString());
If the output for the passed in date is the same as the output for the date that stores the first day of the current month, then the passed in date stores the first date of the current month.
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.