JavaScript:如何计算 2 天前的日期?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13838441/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript: how to calculate the date that is 2 days ago?
提问by dat789
Possible Duplicate:
Subtract days from a date in javascript
可能的重复:
从 javascript 中的日期中减去天数
I have got a JavaScript that basically returns a date that is 2 days ago. It is as follows:
我有一个 JavaScript,它基本上返回 2 天前的日期。如下:
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);
Assuming today is 12-December-2012, the above will return the date 10-December-2012. I don't think this will work dynamically as we move forward into a new month, OR, change the day from -2 to -15. It will work only from the 3rd of the month.
假设今天是 12-December-2012,上面的将返回日期 10-December-2012。我认为这不会随着我们进入新的月份或将日期从 -2 更改为 -15 而动态地起作用。它将仅从本月 3 日起生效。
How can I modify this so when it is 12-December-2012 today and I want it to return me the date 15 days ago it should be 27-November-2012... and not -3-December-2012?
我该如何修改它,以便今天是 2012 年 12 月 12 日,我希望它返回 15 天前的日期,它应该是 27-November-2012...而不是 -3-December-2012?
Any help appreciated. Thanks! I'm a Javascript newbie.
任何帮助表示赞赏。谢谢!我是 Javascript 新手。
回答by RobG
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());
回答by pfried
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
日期可作为以毫秒为单位的数字,您今天减去两天并使用该毫秒数创建一个新日期

