我有以下测试代码:
var d1 : Date = new Date("2016/02/20 15:00:00 UTC-0000");
trace(d1.toUTCString());
d1.monthUTC++;
trace(d1.toUTCString());
var d2 : Date = new Date("2016/03/31 15:00:00 UTC-0000");
trace(d2.toUTCString());
d2.monthUTC++;
trace(d2.toUTCString());
这痕迹
[trace] Sat Feb 20 15:00:00 2016 UTC
[trace] Sun Mar 20 15:00:00 2016 UTC
[trace] Thu Mar 31 15:00:00 2016 UTC
[trace] Sun May 1 15:00:00 2016 UTC
为什么第二个示例中的日期会跳 1 个月又 1 天,而不是仅仅跳一个月? (3月31日至5月1日)?
最佳答案
我认为解决方案在于 Date 类的内部工作方式:
例如,当我将日期设置为该月 31 日时:
"2016/03/31 15:00:00 UTC-0000"
我将月份加一,在内部它变成:
"2016/04/31 15:00:00 UTC-0000"
然后这个问题又在内部解决了。但由于 4 月只有 30 天,日期溢出到 5 月:
“2016/05/01 15:00:00 UTC-0000”
如果我尝试将日期
字段设置为 4 月 31 日,也会发生同样的情况。
这也意味着官方 ActionScript 文档是错误的:
setUTCMonth()
Sets the month, and optionally the day, in universal time(UTC) and returns the new time in milliseconds. Calling this method does not modify the other fields, but the Date.getUTCDay() and Date.getDay() methods might report a new value if the day of the week changes as a result of calling this method.
他们没有考虑到这种边缘情况,设置月份也会改变日期。
同样的事情也发生在 JavaScript 中。
关于javascript - 日期类 setMonth 设置奇怪的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35822352/