Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to subtract one month from 2015-12-31 but it gives me 2015-12-01 instead of 2015-11-30. Why ?

Code:

var date1 = new Date('2015-12-31');
var date2 = new Date(date1);

date2.setMonth(date1.getMonth() - 1);
console.log(date1);
console.log(date2);

Output:

Thu Dec 31 2015 01:00:00 GMT+0100 (CET)
Tue Dec 01 2015 01:00:00 GMT+0100 (CET)

Any workaround?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
348 views
Welcome To Ask or Share your Answers For Others

1 Answer

When subtracting months, you can check whether the day of the adjusted Date is different to the day of the initial Date. If it is, then it must have rolled over to the next month, so set the day of the adjusted Date to 0, so it goes to the last day of the previous month, e.g.

function subtractMonths(date, months) {
  var day = date.getDate();
  date.setMonth(date.getMonth() - months);
  if (date.getDate() != day) date.setDate(0);
  return date;
}

// 31 Mar 2016 - 1 month = 29 Feb 2015
[[new Date(2016,2,31), 1],

 // 29 Feb 2016 - 12 months = 28 Feb 2015
 [new Date(2016,1,29), 12],

 // 15 Feb 2016 - 3 months = 15 Nov 2015
 [new Date(2016,1,15), 3]].forEach(function(arr){
  document.write('<br>' + subtractMonths(arr[0], arr[1]));
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...