Borislav Hadzhiev
Wed Jan 26 2022·2 min read
Photo by Allef Vinicius
To check if a date is the first day of the month:
getDate()
method to get the day of the month for the given date.1
, the date is the first day of the month.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:
Date
object that stores the first day of the current month.toDateString()
method on both dates.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.
// 👇️ Wed Jan 26 2022 console.log(new Date().toDateString());