Using the getDate()
method, you can check if a date is the first day of the month.
When you call the getDate()
method on the given Date object, you get an integer value between 1 and 31. This value is the month's date. If it is equal to 1, then the date is the first day of the month.
let d1 = new Date('2022-02-21'); if(d1.getDate() === 1){ console.log('The given Date d1 is the first day of the month.'); }else{ console.log('The given Date d1 is not the first day of the month.'); } let d2 = new Date('2022-03-01'); if(d2.getDate() === 1){ console.log('The given Date d2 is the first day of the month.'); }else{ console.log('The given Date d2 is not the first day of the month.'); }
Output
The given Date d1 is not the first day of the month. The given Date d2 is the first day of the month.
In this example, two date objects are created. The first Date
object represents 21st February as it is not the first day of the month; that is why the getDate()
method returns 21.
On the other hand, the second Date
object represents 1st March. So on calling the getDate()
method, you got 1, and the condition evaluates to true
, and a message is printed.