Get the First day of the Previous Month #
To get the first day of the previous month, use the Date() constructor to create a date object, passing it a call to the getFullYear() method for the year, a call to the getMonth() method - 1 to get the previous month and 1 for the day.
Copied!
function getFirstDayPreviousMonth() { const date = new Date(); return new Date(date.getFullYear(), date.getMonth() - 1, 1); } console.log(getFirstDayPreviousMonth());We passed the following 3 arguments to the Date() constructor:
- The year
- The month - notice that we subtracted 1 from the return value of the getMonth method to get the previous month.
- The day
We used the Date.getFullYear method to get the current year.
We used the Date.getMonth method to get the current month.
The getMonth method returns an integer from 0 (January) to 11 (December).
Months are zero-based in JavaScript and go from 0 (January) to 11 (December).
We hard-coded 1 for the day because we want the first day of the month.
To make your code more readable, you could extract the values for the previous month and the day in variables.
Copied!
function getFirstDayPreviousMonth() { const date = new Date(); const prevMonth = date.getMonth() - 1; const firstDay = 1; return new Date(date.getFullYear(), prevMonth, firstDay); } console.log(getFirstDayPreviousMonth());This function would also work if the previous month is December of last year.
Copied!
// 👉️ Sun Dec 01 2024 console.log(new Date(2025, 0 - 1, 1));Because of how dates work in JavaScript, the value of the year gets rolled back if we subtract 1 month from January.
The tricky thing to remember is that months are zero-based and go from 0 (January) to 11 (December).
Further Reading #
- Get First and Last Day of the Current Month in JavaScript
- Get the Last Day of a Month in JavaScript
In this tutorial, we are going to learn about how to get the previous month name using the current date in JavaScript.
Getting the previous month name
To get the previous month name, first we need to access the current date object using the new Date() constructor.
const current = new Date();
Now, we need to subtract the current month with -1 and set it to the current date using the setMonth()and getMonth() methods.
current.setMonth(current.getMonth()-1); const previousMonth = current.toLocaleString('default', { month: 'long' }); console.log(previousMonth); // "September"
Definitions
setMonth() : The setMonth() sets the month to a date object.
getMonth(): The getMonth() month returns the month in number format (from 0 - 11).
Note: 0 represents January, 1 represents February, and so on.
toLocaleString(): The toLocaleString() formats the date into a specified format.
You can also read, how to get a current month name in JavaScript.