gpt4 book ai didi

javascript - 在日期中添加月份在 JavaScript 中不起作用

转载 作者:行者123 更新时间:2023-11-30 19:56:41 25 4
gpt4 key购买 nike

我只想将 45 个月添加到 JavaScript 中的给定日期。我 试过这个:

var startDateFormat = new Date(2018, 11, 24); // 11 is for January starts from 0
var addDate = startDateFormat.setMonth(startDateFormat.getMonth() + 45); //want to add 45 months
console.log(new Date(addDate).getFullYear() + "-" + new Date(addDate).getMonth() + 1 + "-" + new Date(addDate).getUTCDate())

但是结果是2019-101-23。谁能帮我解释为什么会这样?

最佳答案

这里有几个问题:

  • setMonth 修改您调用它的实例的状态,您通常不使用它的返回值。
  • 您在 getMonth 之后执行的 + 1 是将 “1” 添加到 string。如果您想要它的数字形式,请将其与 getMonth 分组。
  • 不要结合使用 UTC 方法和非 UTC 方法,在所有调用中使用 UTC 或都不使用 UTC。
  • 您不必到处创建新日期,您可以只使用第一个日期。
  • 不太确定您所说的“11 表示一月从 0 开始”的评论是什么意思。 11 是十二月,而不是一月。

所以:

var dt = new Date(2018, 11, 24); // 11 is for January starts from 0
dt.setMonth(dt.getMonth() + 45); //want to add 45 months
console.log(dt.getFullYear() + "-" + (dt.getMonth() + 1) + "-" + dt.getDate());
// Note parens ----------------------^-----------------^

关于javascript - 在日期中添加月份在 JavaScript 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53911982/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com