How to calculate the date three months prior using JavaScript?


To calculate the date three months prior using JavaScript, we will first need to create a new date object, which will represent the current date. We will then use the setMonth() method to subtract 3 from the current month. Finally, we will convert this new date object back to a string using the toString method to display the date three months prior.

Basically, we will be writing a dynamic JavaScript function that can take in a number as its input and return the date prior to that number of months from today’s date.

For example −

calculatePriorDate(4);

This function should return 19/09/2022 assuming that today’s date is 19/01/2023 in DD/MM/YYYY format.

Approach

  • This is a simple functionality and can be achieved using the native JS Date Object.

  • We will be using the JS Date getMonth and setMonth methods to respectively get and set new months.

  • The function responsible for doing the will look like −

const calculatePriorDate = (priorMonths = 1) => {
  	const date = new Date();
 	 
  	// accessing current month of the date
  	const currentMonth = date.getMonth();
 	 
  	// subtracting required number of months
  	date.setMonth(currentMonth - priorMonths);
 	 
  	return date.toLocaleDateString();
};

This function will simply take in the month gap and return the prior date string after subtracting the required number of months.

Example

The full working code for this functionality will be −

<!DOCTYPE html>
<html>
<head>
   <title>Prior Date</title>
   <style>
      #space {
         color: black;
      }
   </style>
</head>
   <body>
      <input placeholder = 'Input Gap...' id = 'gap' />
      <button onclick = 'renderGap()'>Calculate</button>
      <p id = 'space'></p>
      <script>       
         const calculatePriorDate = (priorMonths = 1) => {
            const date = new Date();
         
            // accessing current month of the date
            const currentMonth = date.getMonth();
         
            // subtracting required number of months
            date.setMonth(currentMonth - priorMonths); 	 
            return date.toLocaleDateString();
         };    
         const renderGap = () => {
            const space = document.getElementById('space');
            const gapInput = document.getElementById('gap'); 	 
            const gap = parseInt(gapInput.value) || 1;
            const newDate = calculatePriorDate(gap);	 
            space.innerText = newDate;	 
         }
      </script>
   </body>
</html>

Updated on: 16-Feb-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements