gpt4 book ai didi

javascript - javascript日期构造函数中的日期溢出

转载 作者:行者123 更新时间:2023-12-03 11:24:06 25 4
gpt4 key购买 nike

我目前正在编写某种基于 javascript 的客户端日历并发现了一些问题。在整个网络中,我可以找到代码示例,其中人们在 Date 构造函数中使用日期溢出。

// get the first day of the next month
var myDate = new Date(someDate.getFullYear(),someDate.getMonth(),32);
myDate.setDate(1);

这个概念的总体思路是,由于没有 32 天的月份,构造函数将在下个月内创建一个日期。我什至看到了带有负溢出的代码示例:

// get the last day of the previous month
var myDate = new Date(someDate.getFullYear(),someDate.getMonth(),1);
myDate.setDate(-1);

虽然这似乎在很多情况下都有效,但我终于发现了一个矛盾:

// this prints "2012-12-30" expected was "2012-12-31"
var myDate = new Date(2013,0,1);
myDate.setDate(-1);

进一步检查最终发现日期像new Date(2013,0,23) 或 new Date(2013,0,16) 结合 setDate(-1) 都以“2012-12-31”结束。最后我观察到使用 -1 似乎减去了两天(为了获得预期的结果必须使用 setDate(0))。

这是浏览器实现中的错误还是代码示例在 Internet 垃圾中传播?

此外,这个带有正负溢出的setDate是否安全,可以被所有主流浏览器使用和统一实现?

最佳答案

来自 MDN :

If the parameter you specify is outside of the expected range, setDate attempts to update the date information in the Date object accordingly. For example, if you use 0 for dayValue, the date will be set to the last day of the previous month.

如果您考虑一下,这是合乎逻辑的:setDate(1) 将日期设置为该月的第一天。要获得上个月的最后一天,即本月第一天的前一天,您可以从参数中减去一个并得到 0。如果减去两天 (1 - 2),您将得到倒数第二天 (-1)。

are [..] code samples spread accross the internet crap?

是的。至少在 90% 的情况下都是如此。

关于javascript - javascript日期构造函数中的日期溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14121363/

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