在javascript中添加一天到目前为止

kar*_*tal 29 javascript date

我确信很多人都会问这个问题,但当我检查答案时,在我看来,我发现它们是错误的

var startDate = new Date(Date.parse(startdate));
//The start date is right lets say it is 'Mon Jun 30 2014 00:00:00'

var endDate = new Date(startDate.getDate() + 1);
// the enddate in the console will be 'Wed Dec 31 1969 18:00:00' and that's wrong it should be  1 july 
Run Code Online (Sandbox Code Playgroud)

我知道.getDate()从1-31返回但是浏览器或javascript只增加了一天没有更新月份和年份?

在这种情况下,我应该写一个算法来处理这个?还是有另一种方式?

Aev*_*eus 54

请注意,Date.getDate仅返回该月的某一天.您可以通过拨打Date.setDate和附加1 来添加一天.

// Create new Date instance
var date = new Date()

// Add a day
date.setDate(date.getDate() + 1)
Run Code Online (Sandbox Code Playgroud)

JavaScript会自动为您更新月份和年份.

编辑:
这是一个链接到一个页面,你可以找到有关内置Date对象的所有很酷的东西,看看有什么可能:日期.

  • 有时这似乎只增加了 23 小时。有什么原因可能会发生吗? (3认同)

Aus*_*rst 12

Date采用单个数字的构造函数期望自1969年12月31日以来的毫秒数.

Date.getDate()返回当前日期对象的日期索引.在你的例子中,这一天是30.最后的表达是31,因此它在1969年12月31日之后返回了31毫秒.

使用现有方法的简单解决方案是使用Date.getTime().然后,添加一天的毫秒而不是1.

例如,

var dateString = 'Mon Jun 30 2014 00:00:00';

var startDate = new Date(dateString);

// seconds * minutes * hours * milliseconds = 1 day 
var day = 60 * 60 * 24 * 1000;

var endDate = new Date(startDate.getTime() + day);
Run Code Online (Sandbox Code Playgroud)

的jsfiddle

请注意,此解决方案不能处理与夏令时,闰年等相关的边缘情况.相反,使用像moment.js这样的成熟开源库来处理所有内容时,总是一种更具成本效益的方法.

  • 此解决方案不考虑“节省天数”的更改,当一天可能恰好长或短一小时时。 (2认同)

HJ0*_*J05 6

我认为您正在寻找的是:

startDate.setDate(startDate.getDate() + 1);
Run Code Online (Sandbox Code Playgroud)

另外,你可以看看Moment.js

用于解析、验证、操作和格式化日期的 JavaScript 日期库。


小智 5

使用这个我认为它对你有用

var endDate=startDate.setDate(startDate.getDate() + 1);
Run Code Online (Sandbox Code Playgroud)


Bla*_*mba 5

2 月 31 日和 28 日有问题,getDate()我使用此功能getTime并且24*60*60*1000 = 86400000

var dateWith31 = new Date("2017-08-31");
var dateWith29 = new Date("2016-02-29");

var amountToIncreaseWith = 1; //Edit this number to required input

console.log(incrementDate(dateWith31,amountToIncreaseWith));
console.log(incrementDate(dateWith29,amountToIncreaseWith));

function incrementDate(dateInput,increment) {
        var dateFormatTotime = new Date(dateInput);
        var increasedDate = new Date(dateFormatTotime.getTime() +(increment *86400000));
        return increasedDate;
    }
Run Code Online (Sandbox Code Playgroud)


MgC*_*eur 5

在 JavaScript 中一行添加一天

注意:如果您想添加特定天数...只需将 1 替换为您想要的天数


new Date(new Date().setDate(new Date().getDate() + 1))
Run Code Online (Sandbox Code Playgroud)

new Date(new Date().setDate(new Date().getDate() + 1))
Run Code Online (Sandbox Code Playgroud)