Use the setMonth()
method of the Date
object to date minus 1 month in JavaScript. This involves getting the current month and year of the date, setting the month to one month earlier, and adjusting the year if necessary.
JavaScript date minus 1-month example
A simple example code gets the date in JavaScript that is one month earlier than a given date
<!DOCTYPE html>
<html>
<body>
<script>
// Create a new date object
let myDate = new Date('2023-03-28');
// Get the month and year of the current date
let currentMonth = myDate.getMonth();
let currentYear = myDate.getFullYear();
// Set the month to one month earlier
myDate.setMonth(currentMonth - 1);
// If the current month was January, set the year to the previous year
if (currentMonth === 0) {
myDate.setFullYear(currentYear - 1);
}
console.log(myDate.toLocaleDateString());
console.log(myDate)
</script>
</body>
</html>
Output:
Do comment if you have any doubts or suggestions on this Js date topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version