JavaScript:如何计算2天前的日期? [英] JavaScript: how to calculate the date that is 2 days ago?
问题描述
可能重复:
从javascript中的日期中减去天数
我有一个JavaScript,该JavaScript基本上会返回2天前的日期.如下:
I have got a JavaScript that basically returns a date that is 2 days ago. It is as follows:
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号开始工作.
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.
如何修改此设置,以便今天是2012年12月12日,并且希望它将15天前的日期还给我,所以应该是2012年11月27日...而不是2012年12月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?
任何帮助表示赞赏.谢谢!我是Java语言新手.
Any help appreciated. Thanks! I'm a Javascript newbie.
推荐答案
如果有日期对象,则可以通过从日期中减去两天来将其设置为前两天:
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());
这篇关于JavaScript:如何计算2天前的日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!