在 javascript/typescript 中添加日期到日期给出了完全错误的日期

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

Adding days to Date in javascript / typescript gives completely wrong date

javascriptdatedatetimetimetypescript

提问by ganjan

I have this very simple code, and it works sometimes but other times it gives the complete wrong date:

我有这个非常简单的代码,它有时会起作用,但有时它会给出完全错误的日期:

  addDays(date: Date, days: number): Date {
    console.log('adding ' + days + ' days');
    console.log(date);
    date.setDate(date.getDate() + days);
    console.log(date);
    return date;
  }

Here is an example of the output:

下面是一个输出示例:

Works!

作品!

adding 7 days
error-chart.component.ts:118 Tue Aug 02 2016 00:00:00 GMT+0200 (Vest-Europa (sommertid))
error-chart.component.ts:120 Tue Aug 09 2016 00:00:00 GMT+0200 (Vest-Europa (sommertid))

Stops working:

停止工作:

adding 14 days
error-chart.component.ts:118 Tue Aug 02 2016 00:00:00 GMT+0200 (Vest-Europa (sommertid))
error-chart.component.ts:120 Thu Mar 02 2017 00:00:00 GMT+0100 (Vest-Europa (normaltid))

somehow jumps 2 years

不知何故跳了2年

adding 14 days
error-chart.component.ts:118 Thu Jul 07 2016 00:00:00 GMT+0200 (Vest-Europa (sommertid))
error-chart.component.ts:120 Thu Jun 14 2018 00:00:00 GMT+0200 (Vest-Europa (sommertid))

now 4 years!

现在4年了!

adding 14 days
error-chart.component.ts:118 Thu Jun 14 2018 00:00:00 GMT+0200 (Vest-Europa (sommertid))
error-chart.component.ts:120 Thu Apr 14 2022 00:00:00 GMT+0200 (Vest-Europa (sommertid))

回答by Lajos Arpad

You have a problem with types. If daysis 14, then it will yield 16th August correctly. However, if daysis "14", then it will yield 2nd of March.

你的类型有问题。如果days是 14,那么它将正确产生 16th August。但是,如果days是“14”,那么它将产生 3 月 2 日。

Solution:

解决方案:

  addDays(date: Date, days: number): Date {
    console.log('adding ' + days + ' days');
    console.log(date);
    date.setDate(date.getDate() + parseInt(days));
    console.log(date);
    return date;
  }