javascript日期库重复十月

javascript Date library repeating October

本文关键字:十月 日期 javascript      更新时间:2023-09-26

在试图找出我在处理日历时遇到问题的原因时,我遇到了这个问题。当将月份设置为8时,日期设置为10月,当将月份设为9时,日期设为10月。测试的代码

var d = new Date();
document.write(d.getMonth());
d.setMonth(8);
document.write(d.getMonth());
d.setMonth(9);
document.write(d.getMonth());
output:
799

当前日期是2012年8月31日,月份号应该是7,因为javascript月份是基于0的。

有人能解释一下吗?我已经能够在不止一台电脑上复制它了。

9月只有30天-当您将日期设置为31(或在某个月的31日创建日期),然后将该月更改为少于31天的月份时,JavaScript会将日期滚动到下一个月(在本例中为10月)。换句话说,日期溢出。

> var d = new Date()
> d
Fri Aug 31 2012 22:53:50 GMT-0400 (EDT)
// Set the month to September, leaving the day set to the 31st
> d.setMonth(8) 
> d
Mon Oct 01 2012 22:53:50 GMT-0400 (EDT)
// Doing the same thing, changing the day first
> var d = new Date()
> d
Fri Aug 31 2012 22:53:50 GMT-0400 (EDT)
> d.setDate(30)
> d
Thu Aug 30 2012 22:53:50 GMT-0400 (EDT)
> d.setMonth(8)
Sun Sep 30 2012 22:53:50 GMT-0400 (EDT)

所以简单的答案是,因为今天的日期是8月31日,9月31日是10月1日。