javascript 如何通过在javascript中给出天数来增加日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8223994/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 02:42:20  来源:igfitidea点击:

how to increment date by giving the number of days in javascript

javascriptdate

提问by Bader

I want to increment dates using JavaScript I used .setDate(1)to increment dates by one day but if the date is 31/11/2011after increment becomes 1/0/2012,

我想使用 JavaScript 增加日期我曾经.setDate(1)将日期增加一天,但如果日期31/11/2011在增加之后变为1/0/2012

the question is how to increment date by giving the number of days .

问题是如何通过给出天数来增加日期。

js

js

  newDate.setDate(newDate.getDate()+1);
    alert(newDate.getFullYear()+"-"+newDate.getMonth()+"-"+newDate.getDate());  

回答by Dogbert

That is correct, because in javascript, months are indexed from 0, not 1.

这是正确的,因为在 javascript 中,月份是从 0 开始索引的,而不是 1。

You need to alert like this instead:

你需要像这样提醒:

alert(newDate.getFullYear()+"-"+(newDate.getMonth()+1)+"-"+newDate.getDate());  

回答by Ioannis Karadimas

That is not wrong, given that months in Javascript dates range from 0 to 11. So when you speak of 31/11/2011, what javascript understands is 31/12/2011.

这并没有错,因为 Javascript 中的月份日期范围从 0 到 11。所以当你谈到 时31/11/2011,javascript 理解的是31/12/2011.

回答by AlphaMale

Lets make it some more clear:

让我们说得更清楚一些:

var Date = new Date();
var DaysToAdd = 6;
someDate.setDate(Date.getDate() + DaysToAdd); 

Formatting Date to dd/mm/yyyy format:

将日期格式化为 dd/mm/yyyy 格式:

var dd = Date.getDate();
var mm = Date.getMonth() + 1;
var yyyy = Date.getFullYear();

var NewDate = dd + '/'+ mm + '/'+ yyyy;

Hope this helps.

希望这可以帮助。

回答by Stuti

You can use like this, Suppose you want to increment current date by 2 days then,

您可以这样使用,假设您想将当前日期增加 2 天,然后,

var today = new Date(); // Or Date.today()
var newDate = today.add(2).day();