在 JavaScript 中增加日期

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

Incrementing a date in JavaScript

javascriptdatedatetime

提问by Santanu

I need to increment a date value by one day in JavaScript.

我需要在 JavaScript 中将日期值增加一天。

For example, I have a date value 2010-09-11 and I need to store the date of the next day in a JavaScript variable.

例如,我有一个日期值 2010-09-11,我需要将第二天的日期存储在 JavaScript 变量中。

How can I increment a date by a day?

如何将日期增加一天?

回答by T.J. Crowder

Three options for you:

三种方案供您选择:

1. Using just JavaScript's Dateobject (no libraries):

1. 只使用 JavaScript 的Date对象(没有库):

My previous answer for #1 was wrong (it added 24 hours, failing to account for transitions to and from daylight saving time; Clever Humanpointed out that it would fail with November 7, 2010 in the Eastern timezone). Instead, Jigar's answeris the correct way to do this without a library:

我之前对 #1 的回答是错误的(它增加了 24 小时,没有考虑到夏令时的转换;Clever Human指出它会在东部时区的 2010 年 11 月 7 日失败)。相反,Jigar 的答案是在没有图书馆的情况下做到这一点的正确方法:

var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);

This works even for the last day of a month (or year), because the JavaScript date object is smart about rollover:

这甚至适用于一个月(或一年)的最后一天,因为 JavaScript 日期对象在翻转方面很聪明:

var lastDayOf2015 = new Date(2015, 11, 31);
snippet.log("Last day of 2015: " + lastDayOf2015.toISOString());
var nextDay = new Date(+lastDayOf2015);
var dateValue = nextDay.getDate() + 1;
snippet.log("Setting the 'date' part to " + dateValue);
nextDay.setDate(dateValue);
snippet.log("Resulting date: " + nextDay.toISOString());
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

(This answer is currently accepted, so I can't delete it. Before it was accepted I suggested to the OP they accept Jigar's, but perhaps they accepted this one for items #2 or #3 on the list.)

(这个答案目前已被接受,所以我不能删除它。在它被接受之前,我建议 OP 他们接受 Jigar 的,但也许他们接受了这个列表中的第 2 项或第 3 项。)

2. Using MomentJS:

2. 使用MomentJS

var today = moment();
var tomorrow = moment(today).add(1, 'days');

(Beware that addmodifies the instance you call it on, rather than returning a new instance, so today.add(1, 'days')would modify today. That's why we start with a cloning op on var tomorrow = ....)

(请注意,add修改您调用它的实例,而不是返回一个新实例,因此today.add(1, 'days')将修改today。这就是我们从 克隆操作开始的原因var tomorrow = ...。)

3. Using DateJS, but it hasn't been updated in a long time:

3.使用DateJS,但好久没更新了:

var today = new Date(); // Or Date.today()
var tomorrow = today.add(1).day();

回答by Jigar Joshi

var myDate = new Date();

//add a day to the date
myDate.setDate(myDate.getDate() + 1);

回答by CleverPatrick

None of the examples in this answer seem to work with Daylight Saving Time adjustment days. On those days, the number of hours in a day are not 24 (they are 23 or 25, depending on if you are "springing forward" or "falling back".)

此答案中的所有示例似乎都不适用于夏令时调整日。在那些日子里,一天中的小时数不是 24(它们是 23 或 25,取决于你是“向前”还是“后退”。)

The below AddDays javascript function accounts for daylight saving time:

下面的 AddDays javascript 函数说明了夏令时:

function addDays(date, amount) {
  var tzOff = date.getTimezoneOffset() * 60 * 1000,
      t = date.getTime(),
      d = new Date(),
      tzOff2;

  t += (1000 * 60 * 60 * 24) * amount;
  d.setTime(t);

  tzOff2 = d.getTimezoneOffset() * 60 * 1000;
  if (tzOff != tzOff2) {
    var diff = tzOff2 - tzOff;
    t += diff;
    d.setTime(t);
  }

  return d;
}

Here are the tests I used to test the function:

以下是我用来测试该功能的测试:

    var d = new Date(2010,10,7);
    var d2 = AddDays(d, 1);
    document.write(d.toString() + "<br />" + d2.toString());

    d = new Date(2010,10,8);
    d2 = AddDays(d, -1)
    document.write("<hr /><br />" +  d.toString() + "<br />" + d2.toString());

    d = new Date('Sun Mar 27 2011 01:59:00 GMT+0100 (CET)');
    d2 = AddDays(d, 1)
    document.write("<hr /><br />" +  d.toString() + "<br />" + d2.toString());

    d = new Date('Sun Mar 28 2011 01:59:00 GMT+0100 (CET)');
    d2 = AddDays(d, -1)
    document.write("<hr /><br />" +  d.toString() + "<br />" + d2.toString());

回答by Sylvain Lecorné

The easiest way is to convert to milliseconds and add 1000*60*60*24 milliseconds e.g.:

最简单的方法是转换为毫秒并添加 1000*60*60*24 毫秒,例如:

var tomorrow = new Date(today.getTime()+1000*60*60*24);

回答by jpmottin

Tomorrow in one line in pure JS but it's ugly!

明天在纯 JS 中一行,但它很丑

new Date(new Date().setDate(new Date().getDate() + 1))

Here is the result :

结果如下:

Thu Oct 12 2017 08:53:30 GMT+0200 (Romance Summer Time)

回答by einarmagnus

You first need to parse your string before following the other people's suggestion:

在遵循其他人的建议之前,您首先需要解析您的字符串:

var dateString = "2010-09-11";
var myDate = new Date(dateString);

//add a day to the date
myDate.setDate(myDate.getDate() + 1);

If you want it back in the same format again you will have to do that "manually":

如果您希望它再次以相同的格式返回,则必须“手动”执行此操作:

var y = myDate.getFullYear(),
    m = myDate.getMonth() + 1, // january is month 0 in javascript
    d = myDate.getDate();
var pad = function(val) { var str = val.toString(); return (str.length < 2) ? "0" + str : str};
dateString = [y, pad(m), pad(d)].join("-");

But I suggest getting Date.js as mentioned in other replies, that will help you alot.

但是我建议按照其他回复中提到的方式获取 Date.js,这将对您有很大帮助。

回答by Polv

I feel that nothing is safer than .getTime()and .setTime(), so this should be the best, and performant as well.

我觉得没有什么比.getTime()and更安全的了.setTime(),所以这应该是最好的,也是性能最好的。

const d = new Date()
console.log(d.setTime(d.getTime() + 1000 * 60 * 60 * 24)) // MILLISECONDS

.setDate()for invalid Date (like 31 + 1) is too dangerous, and it depends on the browser implementation.

.setDate()对于无效日期(如 31 + 1)太危险了,这取决于浏览器的实现。

回答by fitodac

Getting the next 5 days:

获得接下来的 5 天:

var date = new Date(),
d = date.getDate(),
m = date.getMonth(),
y = date.getFullYear();


for(i=0; i < 5; i++){
var curdate = new Date(y, m, d+i)
console.log(curdate)
}

回答by Laksh Goel

Two methods:

两种方法:

1:

1:

var a = new Date()
// no_of_days is an integer value
var b = new Date(a.setTime(a.getTime() + no_of_days * 86400000)

2: Similar to the previous method

2:与之前的方法类似

var a = new Date()
// no_of_days is an integer value
var b = new Date(a.setDate(a.getDate() + no_of_days)

回答by swirekx

 Date.prototype.AddDays = function (days) {
    days = parseInt(days, 10);
    return new Date(this.valueOf() + 1000 * 60 * 60 * 24 * days);
}

Example

例子

var dt = new Date();
console.log(dt.AddDays(-30));
console.log(dt.AddDays(-10));
console.log(dt.AddDays(-1));
console.log(dt.AddDays(0));
console.log(dt.AddDays(1));
console.log(dt.AddDays(10));
console.log(dt.AddDays(30));

Result

结果

2017-09-03T15:01:37.213Z
2017-09-23T15:01:37.213Z
2017-10-02T15:01:37.213Z
2017-10-03T15:01:37.213Z
2017-10-04T15:01:37.213Z
2017-10-13T15:01:37.213Z
2017-11-02T15:01:37.213Z