Skip to content

JavaScript date minus 1 month

  • by

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:

JavaScript date minus 1 month

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

Tags:

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading