[javascript] How do I calculate the date in JavaScript three months prior to today?

I Am trying to form a date which is 3 months before the current date. I get the current month by the below code

var currentDate = new Date();
var currentMonth = currentDate.getMonth()+1;

Can you guys provide me the logic to calculate and form a date (an object of the Date data type) considering that when the month is January (1), 3 months before date would be OCtober (10)?

This question is related to javascript date

The answer is


I recommend using a library called Moment.js.

It is well tested, works cross browser and on server side(I am using it both in Angular and Node projects). It has great support for locale dates.

http://momentjs.com/

var threeMonthsAgo = moment().subtract(3, 'months');

console.log(threeMonthsAgo.format()); // 2015-10-13T09:37:35+02:00

.format() returns string representation of date formatted in ISO 8601 format. You can also use it with custom date format like this:.format('dddd, MMMM Do YYYY, h:mm:ss a')


Pass a JS Date object and an integer of how many months you want to add/subtract. monthsToAdd can be positive or negative. Returns a JS date object.

If your originalDateObject is March 31, and you pass -1 as monthsToAdd, then your output date will be February 28.

If you pass a large number of months, say 36, it will handle the year adjustment properly as well.

const addMonthsToDate = (originalDateObject, monthsToAdd) => {
  const originalDay = originalDateObject.getUTCDate();
  const originalMonth = originalDateObject.getUTCMonth();
  const originalYear = originalDateObject.getUTCFullYear();

  const monthDayCountMap = {
    "0": 31,
    "1": 28,
    "2": 31,
    "3": 30,
    "4": 31,
    "5": 30,
    "6": 31,
    "7": 31,
    "8": 30,
    "9": 31,
    "10": 30,
    "11": 31
  };

  let newMonth;
  if (newMonth > -1) {
    newMonth = (((originalMonth + monthsToAdd) % 12)).toString();
  } else {
    const delta = (monthsToAdd * -1) % 12;
    newMonth = originalMonth - delta < 0 ? (12+originalMonth) - delta : originalMonth - delta;
  }

  let newDay;

  if (originalDay > monthDayCountMap[newMonth]) {
    newDay = monthDayCountMap[newMonth].toString();
  } else {
    newDay = originalDay.toString();
  }

  newMonth = (+newMonth + 1).toString();

  if (newMonth.length === 1) {
    newMonth = '0' + newMonth;
  }

  if (newDay.length === 1) {
    newDay = '0' + newDay;
  }

  if (monthsToAdd <= 0) {
    monthsToAdd -= 11;
  }

  let newYear = (~~((originalMonth + monthsToAdd) / 12)) + originalYear;

  let newTime = originalDateObject.toISOString().slice(10, 24);

  const newDateISOString = `${newYear}-${newMonth}-${newDay}${newTime}`;

  return new Date(newDateISOString);
};

_x000D_
_x000D_
var d = new Date();_x000D_
document.write(d + "<br/>");_x000D_
d.setMonth(d.getMonth() - 6);_x000D_
document.write(d);
_x000D_
_x000D_
_x000D_


In my case I needed to substract 1 month to current date. The important part was the month number, so it doesn't care in which day of the current month you are at, I needed last month. This is my code:

var dateObj = new Date('2017-03-30 00:00:00'); //Create new date object
console.log(dateObj); // Thu Mar 30 2017 00:00:00 GMT-0300 (ART)

dateObj.setDate(1); //Set first day of the month from current date
dateObj.setDate(-1); // Substract 1 day to the first day of the month

//Now, you are in the last month
console.log(dateObj); // Mon Feb 27 2017 00:00:00 GMT-0300 (ART)

Substract 1 month to actual date it's not accurate, that's why in first place I set first day of the month (first day of any month always is first day) and in second place I substract 1 day, which always send you to last month. Hope to help you dude.

_x000D_
_x000D_
var dateObj = new Date('2017-03-30 00:00:00'); //Create new date object_x000D_
console.log(dateObj); // Thu Mar 30 2017 00:00:00 GMT-0300 (ART)_x000D_
_x000D_
dateObj.setDate(1); //Set first day of the month from current date_x000D_
dateObj.setDate(-1); // Substract 1 day to the first day of the month_x000D_
_x000D_
//Now, you are in the last month_x000D_
console.log(dateObj); // Mon Feb 27 2017 00:00:00 GMT-0300 (ART)
_x000D_
_x000D_
_x000D_


To make things really simple you can use DateJS, a date library for JavaScript:

http://www.datejs.com/

Example code for you:

Date.today().add({ months: -1 });

_x000D_
_x000D_
var d = new Date("2013/01/01");_x000D_
console.log(d.toLocaleDateString());_x000D_
d.setMonth(d.getMonth() + 18);_x000D_
console.log(d.toLocaleDateString());
_x000D_
_x000D_
_x000D_


_x000D_
_x000D_
   _x000D_
_x000D_
 var date=document.getElementById("date");_x000D_
    var d = new Date();_x000D_
   document.write(d + "<br/>");_x000D_
    d.setMonth(d.getMonth() - 6);_x000D_
    document.write(d);_x000D_
_x000D_
 if(d<date)_x000D_
  document.write("lesser then 6 months");_x000D_
else_x000D_
  document.write("greater then 6 months");
_x000D_
_x000D_
_x000D_


If the setMonth method offered by gilly3 isn't what you're looking for, consider:

var someDate = new Date(); // add arguments as needed
someDate.setTime(someDate.getTime() - 3*28*24*60*60);
// assumes the definition of "one month" to be "four weeks".

Can be used for any amount of time, just set the right multiples.


This should handle addition/subtraction, just put a negative value in to subtract and a positive value to add. This also solves the month crossover problem.

function monthAdd(date, month) {
    var temp = date;
    temp = new Date(date.getFullYear(), date.getMonth(), 1);
    temp.setMonth(temp.getMonth() + (month + 1));
    temp.setDate(temp.getDate() - 1); 

    if (date.getDate() < temp.getDate()) { 
        temp.setDate(date.getDate()); 
    }

    return temp;    
}

There is an elegant answer already but I find that its hard to read so I made my own function. For my purposes I didn't need a negative result but it wouldn't be hard to modify.

    var subtractMonths = function (date1,date2) {
        if (date1-date2 <=0) {
            return 0;
        }
        var monthCount = 0;
        while (date1 > date2){
            monthCount++;
            date1.setMonth(date1.getMonth() -1);
        }
        return monthCount;
    }

This is the Smallest and easiest code.

   var minDate = new Date(); 
   minDate.setMonth(minDate.getMonth() - 3);

Declare variable which has current date. then just by using setMonth inbuilt function we can get 3 month back date.


Following code give me Just Previous Month From Current Month even the date is 31/30 of current date and last month is 30/29/28 days:

   <!DOCTYPE html>
<html>
<body>

<p>Click the button to display the date after changing the month.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {

var d = new Date("March 29, 2017"); // Please Try the result also for "March 31, 2017" Or "March 30, 2017"
var OneMonthBefore =new Date(d);

OneMonthBefore.setMonth(d.getMonth(),0);
if(OneMonthBefore.getDate() < d.getDate()  )
{
d.setMonth(d.getMonth(),0);
}else
{
d.setMonth(d.getMonth()-1);

}

    document.getElementById("demo").innerHTML = d;
}
</script>

</body>
</html>

Do this

 let currentdate = new Date();
 let last3months = new Date(currentdate.setMonth(currentdate.getMonth()-3));

Javascript's setMonth method also takes care of the year. For instance, the above code will return 2020-01-29 if currentDate is set as new Date("2020-01-29")


I like the simplicity of gilly3's answer, but users will probably be surprised that a month before March 31 is March 3. I chose to implement a version that sticks to the end of the month, so a month before March 28, 29, 30, and 31 will all be Feb 28 when it's not a leap year.

_x000D_
_x000D_
function addMonths(date, months) {_x000D_
  var result = new Date(date),_x000D_
      expectedMonth = ((date.getMonth() + months) % 12 + 12) % 12;_x000D_
  result.setMonth(result.getMonth() + months);_x000D_
  if (result.getMonth() !== expectedMonth) {_x000D_
    result.setDate(0);_x000D_
  }_x000D_
  return result;_x000D_
}_x000D_
_x000D_
var dt2004_05_31 = new Date("2004-05-31 0:00"),_x000D_
    dt2001_05_31 = new Date("2001-05-31 0:00"),_x000D_
    dt2001_03_31 = new Date("2001-03-31 0:00"),_x000D_
    dt2001_02_28 = new Date("2001-02-28 0:00"),_x000D_
    result = addMonths(dt2001_05_31, -2);_x000D_
console.assert(dt2001_03_31.getTime() == result.getTime(), result.toDateString());_x000D_
_x000D_
result = addMonths(dt2001_05_31, -3);_x000D_
console.assert(dt2001_02_28.getTime() == result.getTime(), result.toDateString());_x000D_
_x000D_
result = addMonths(dt2001_05_31, 36);_x000D_
console.assert(dt2004_05_31.getTime() == result.getTime(), result.toDateString());_x000D_
_x000D_
result = addMonths(dt2004_05_31, -38);_x000D_
console.assert(dt2001_03_31.getTime() == result.getTime(), result.toDateString());_x000D_
_x000D_
console.log('Done.');
_x000D_
_x000D_
_x000D_


As I don't seem to see it already suggested....

const d = new Date();
const day = d.getDate();
const goBack = 3;
for (let i = 0; i < goBack; i++) d.setDate(0);
d.setDate(day);

This will give you the date of today's date 3 months ago as .setDate(0) sets the date to the last day of last month irrespective of how many days a month contains. day is used to restore today's date value.


A "one liner" (on many line for easy read)) to be put directly into a variable:

var oneMonthAgo = new Date(
    new Date().getFullYear(),
    new Date().getMonth() - 1, 
    new Date().getDate()
);