Sometimes, we want to get the previous month’s first date from current date in JavaScript.
In this article, we’ll look at how to get the previous month’s first date from current date in JavaScript.
How to get the previous month’s first date from current date in JavaScript?
To get the previous month’s first date from current date in JavaScript, we call getMonth
and setMonth
.
For instance, we write
const x = new Date();
x.setDate(1);
x.setMonth(x.getMonth() - 1);
to create date x
.
Then we call setDate
with 1 to set the day of the date to 1.
Next, we call getMonth
to get the month of x
.
We then subtract that by 1 and call setMonth
to set the month to the previous month.
Conclusion
To get the previous month’s first date from current date in JavaScript, we call getMonth
and setMonth
.