JavaScript: 如何计算2天前的日期?

可能的复制品:
在 javascript 中从日期中减去天数

我得到了一个 JavaScript,它基本上返回的是两天前的日期,如下所示:

var x;
var m_names = new Array("January", "February", "March",
"April", "May", "June", "July", "August", "September",
"October", "November", "December");


var d = new Date();
var twoDaysAgo = d.getDate()-2;  //change day here
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
var x = twoDaysAgo + "-" + m_names[curr_month] + "-" + curr_year;


document.write(x);

假设今天是2012年12月12日,以上将返回2012年12月10日。我不认为这将动态工作,因为我们前进到一个新的月份,或,改变一天从 -2到 -15。只能从月3号开始。

我怎样才能修改它,使它在今天是2012年12月12日,并且我希望它返回15天前的日期,它应该是2012年11月27日... 而不是2012年12月3日?

感谢你的帮助,谢谢! 我是个 Javascript 新手。

132022 次浏览

You can do the following

​var date = new Date();
var yesterday = date - 1000 * 60 * 60 * 24 * 2;   // current date's milliseconds - 1,000 ms * 60 s * 60 mins * 24 hrs * (# of days beyond one to go back)
yesterday = new Date(yesterday);
console.log(yesterday);​

The Date is available as a number in miliiseconds, you take today subtract two days and create a new date using that number of milliseconds

If you have a date object, you can set it to two days previous by subtracting two from the date:

var d = new Date();
d.setDate(d.getDate() - 2);
console.log(d.toString());


// First of month
var c = new Date(2017,1,1); // 1 Feb -> 30 Jan
c.setDate(c.getDate() - 2);
console.log(c.toString());


// First of year
var b = new Date(2018,0,1); // 1 Jan -> 30 Dec
b.setDate(b.getDate() - 2);
console.log(b.toString());