Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

javascript - Subtracting 1 month to 2015-12-31 gives 2015-12-01

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

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

1 Reply

0 votes
by (71.8m points)

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]));
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...