gpt4 book ai didi

javascript - 如何可靠地实现 'next'/'previous' 月

转载 作者:行者123 更新时间:2023-11-29 11:01:39 25 4
gpt4 key购买 nike

这是asked (严重)之前 - 我不认为该帖子中的答案真正解决了这个问题,然后它就变得陈旧了。我将尝试通过更清晰的问题演示再次提出问题。

Javascript Date.setMonth() 的实现似乎没有遵循最小惊喜原则。在浏览器控制台中试试这个:

d = new Date('2017-08-31')  // Set to last day of August
d.getMonth() // 7 - months are zero-based
d.setMonth(8) // Try to set the month to 8 (September)
d.getMonth() // 9 - October. WTF Javascript?

类似地:

d = new Date('2017-10-31')
d.getMonth() // 9
d.setMonth(8)
d.getMonth() // 9 (still?)

Linux 上的 Firefox 看起来更糟 - 有时会返回十月份的日期,而 getMonth() 的结果与那个月份不匹配!

我的问题(我认为来自该链接问题的 OP 的问题)是如何始终如一地实现“下一个”/“上一个”月份的功能,例如日期选择器?是否有一种众所周知的方法可以做到这一点,用户不会感到惊讶,例如,当他们在 8 月 31 日开始时跳过 9 月并单击“下一步”?从 1 月 31 日开始更不可预测 - 您将在 3 月 2 日或 3 月 3 日结束,具体取决于是否是闰年!

我个人的看法是,最不意外的是移至下个月/上个月的最后一天。但这需要 setMonth() 实现关心相关月份的天数,而不仅仅是添加/减去固定的持续时间。根据this线程,moment.js 方法是在 30 天内加/减毫秒数,这表明库会容易出现相同的不一致。

最佳答案

一切都简单而合乎逻辑。让我们以您的示例为例,看看 id 做了什么。

所以第一行

d = new Date('2017-08-31')  // Set to last day of August
console.log(d); // "2017-08-31T00:00:00.000Z"
console.log(d.getMonth()); // 7 - months are zero-based

到目前为止一切都很好。下一步:您的评论是这样说的://Try to set the month to 8 (September) 所以尝试还没有结束。您要么将其设置为 9 月,要么不设置。在您的示例中,您将其设置为十月。进一步解释。

d = new Date('2017-08-31')  // Set to last day of August
console.log(d); // "2017-08-31T00:00:00.000Z"
console.log(d.getMonth()); // 7 - months are zero-based
d.setMonth(8) // Try to set the month to 8 (September)
console.log(d); // but now I see I was wrong it is (October)

所以问个好问题是为什么? From MDN

Note: Where Date is called as a constructor with more than one argument, if values are greater than their logical range (e.g. 13 is provided as the month value or 70 for the minute value), the adjacent value will be adjusted. E.g. new Date(2013, 13, 1) is equivalent to new Date(2014, 1, 1), both create a date for 2014-02-01 (note that the month is 0-based). Similarly for other values: new Date(2013, 2, 1, 0, 70) is equivalent to new Date(2013, 2, 1, 1, 10) which both create a date for 2013-03-01T01:10:00.

所以说 9 月只有 30 天,但日期对象有 31 天。这就是为什么它给你的是 10 月而不是 9 月。

最简单的方法是获取您拥有的日期并将其设置为每月的第一天。像这样:

var d = new Date('2017-08-31')  // Set to last day of August
// simplest fix take the date you have and set it to first day of month
d = new Date(d.getFullYear(), d.getMonth(), 1);
console.log(d); // "2017-08-31T00:00:00.000Z"
console.log(d.getMonth()); // 7 - months are zero-based
d.setMonth(8) // Set the month to 8 (September)
console.log(d.getMonth()); // get 8 it is (September)

关于javascript - 如何可靠地实现 'next'/'previous' 月,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46004656/

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