Possible Duplicate:
Zero-based month numbering
我正在读的书中的解释是:“嗯,我的阿姨像其他人一样开始从 1 开始计算她的月份,所以我们减去 1。
这是输入字符串日期:"died 27/04/2006: Black Leclère"
代码如下:
function extractDate(paragraph) {
function numberAt(start, length) {
return Number(paragraph.slice(start, start + length));
}
return new Date(numberAt(11, 4), numberAt(8, 2) - 1,
numberAt(5, 2));
}
alert(extractDate("died 27-04-2006: Black Leclère"));
04 - 1 是 03。但这是输出日期对象:Thu Apr 27 2006 00:00:00
.
知道我们想要的输出并不能解释该语言的异常行为以及随后的 -1 的必要性。请解释一下。
最佳答案
JavaScript Date 对象中表示的月份是从 0 开始的。即,一月表示为 0
,二月表示为 1
,三月表示为 2
,依此类推。
有关为何在多种语言中实现此行为的一些有趣答案,请参阅 Zero-based month numbering .
"the combination of zero-based arrays and 1-based month values does bring a problem. To get the month name of month 9, you would have to get item 8 from the month array. Some developers would be happy with decreasing the month number before getting it's name. Others preferred to change the month into something zero-based since people just want to know the name, not the number. It's a personal view."
关于javascript - 为什么在 JavaScript 中转换为日期对象时要从月份中减去 1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7834266/