为什么在 JavaScript 中转换为日期对象时要从月份中减去 1?
可能的重复:
从零开始的月份编号
我正在读的书中的解释是:“好吧,我的阿姨像其他人一样开始从 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的必要性请解释一下。
Possible Duplicate:
Zero-based month numbering
The explanation in the book I am reading says, "Well, my Aunt starts counting her months from 1 like everyone else, so we subtract 1.
Here's the input string date: "died 27/04/2006: Black Leclère"
Here's the code:
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 is 03. But here's the output date object: Thu Apr 27 2006 00:00:00
.
Knowing what we want for the output doesn't explain the unusual behavior of the language and the subsequent necessity of the -1. Please, explain.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
JavaScript Date 对象中表示的月份是从 0 开始的。也就是说,一月表示为
0
,二月表示为1
,三月表示为2
等。有关为什么此行为的一些有趣答案在多种语言中实现,请参阅从零开始的月份编号。
Months represented in JavaScript Date objects are 0-based. That is, January is represented as
0
, February as1
, March as2
, etc.For some interesting answers as to why this behaviour is implemented across many languages, see Zero-based month numbering.
我认为这样做的技术原因是因为月份是一个枚举字段,这意味着它可以映射到月份名称数组,并且数组从零开始计数,而年和日则不枚举;您总是只需要实际的数值,因此这就是存储的内容。
不过,这是一个完全有效的问题,因为如果您使用月份作为数字,那么它可能看起来有点奇怪(更不用说容易忘记)。
顺便说一句,如果您正在使用日期,特别是从字符串中提取日期并将其格式化为字符串,您可能需要查看 Date.js,这是一个 JavaScript 库,可以为所有此类事情提供很大帮助。
I think the technical reason it does this would be because month is an enumerated field, meaning that it can be mapped to an array of month names, and arrays count from zero, whereas years and days are not enumerated; you always just want the actual number value, so that's what is stored.
It is a perfectly valid question to ask though, because if you're using months as a number then it can seem a bit weird (not to mention easy to forget).
By the way, if you're working with dates, particularly extracting dates from strings and formatting them into strings, you might want to look into Date.js, which is a javascript library that can help a lot with all this kind of thing.