Skip to content
Related Articles
Open in App
Not now

Related Articles

How to calculate the date three months prior using JavaScript ?

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 30 Dec, 2022
Improve Article
Save Article

Given a Date and the task is to get the date three months prior using javascript. 

Approach:

  • First, select the date object.
  • Then use the getMonth() method to get the months.
  • Then subtract three months from the getMonth() method and set it using setMonth() method.

Example 1: This example uses getMonth() and setMonth() methods to get and set the month date. 

html




<body>
    <h1 style="color:green;">
        GeeksForGeeks
    </h1>
    <p id="GFG_UP">
    </p>
    <button onClick="GFG_Fun()">
        click here
    </button>
    <p id="GFG_DOWN">
    </p>
    <script>
        var up = document.getElementById('GFG_UP');
        var down = document.getElementById('GFG_DOWN');
        var d = new Date();
        up.innerHTML = "Today's Date= "+ d.toLocaleDateString();
        function GFG_Fun() {
            d.setMonth(d.getMonth() - 3);
            down.innerHTML = "3 months ago, Date was "
                    + d.toLocaleDateString();
        }
    </script>
</body>

Output:

Calculate the date three months prior

Example 2: This example uses getMonth() and setMonth() methods to get and set the month date as provided. 

html




<body>
  
    <h1 style="color:green;">
        GeeksForGeeks
    </h1>
  
    <p id="GFG_UP">
    </p>
  
    <button onClick="GFG_Fun()">
        click here
    </button>
  
    <p id="GFG_DOWN">
    </p>
  
    <script>
        var up = document.getElementById('GFG_UP');
        var down = document.getElementById('GFG_DOWN');
        var d = new Date("2010/12/02");
          
        up.innerHTML = "Date= "+ d.toLocaleDateString();
          
        function GFG_Fun() {
            d.setMonth(d.getMonth() - 3);
            down.innerHTML = "3 Months ago, Date was "
                    + d.toLocaleDateString();
        }
    </script>
</body>

Output:

Calculate the date three months prior


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!