我需要能够添加1,2,5或10天到今天的日期使用jQuery。
当前回答
如果不需要Date中的时间,那么您可以简单地使用Date对象的方法提取月、年和日,并在Day部分添加“n”天。
var n=5; //number of days to add.
var today=new Date(); //Today's Date
var requiredDate=new Date(today.getFullYear(),today.getMonth(),today.getDate()+n)
参考:Mozilla Javascript GetDate
编辑:参考:Mozilla JavaScript日期
其他回答
你可以使用JavaScript,不需要jQuery:
var someDate = new Date();
var numberOfDaysToAdd = 6;
var result = someDate.setDate(someDate.getDate() + numberOfDaysToAdd);
console.log(new Date(result))
您可以像这样扩展javascript Date对象
Date.prototype.addDays = function(days) {
this.setDate(this.getDate() + parseInt(days));
return this;
};
在javascript代码中,你可以调用
var currentDate = new Date();
// to add 4 days to current date
currentDate.addDays(4);
如果不需要Date中的时间,那么您可以简单地使用Date对象的方法提取月、年和日,并在Day部分添加“n”天。
var n=5; //number of days to add.
var today=new Date(); //Today's Date
var requiredDate=new Date(today.getFullYear(),today.getMonth(),today.getDate()+n)
参考:Mozilla Javascript GetDate
编辑:参考:Mozilla JavaScript日期
这里有一个对我有用的解决办法。
function calduedate(ndays){
var newdt = new Date(); var chrday; var chrmnth;
newdt.setDate(newdt.getDate() + parseInt(ndays));
var newdate = newdt.getFullYear();
if(newdt.getMonth() < 10){
newdate = newdate+'-'+'0'+newdt.getMonth();
}else{
newdate = newdate+'-'+newdt.getMonth();
}
if(newdt.getDate() < 10){
newdate = newdate+'-'+'0'+newdt.getDate();
}else{
newdate = newdate+'-'+newdt.getDate();
}
alert("newdate="+newdate);
}
这里公认的答案给了我不可预测的结果,有时会奇怪地加上月和年。
我能找到的最可靠的方法就是在这里 将日期添加到Javascript Date对象,并增加月份
var dayOffset = 20;
var millisecondOffset = dayOffset * 24 * 60 * 60 * 1000;
december.setTime(december.getTime() + millisecondOffset);
编辑:尽管它对一些人有效,但我不认为它是完全正确的。我建议你用一个更流行的答案,或者使用http://momentjs.com/这样的东西