用数字创建日期(新日期(2012年,03年,...)给出错误的月份(+1) [英] Creating date with numbers (new Date(2012, 03, ...) gives wrong month (+1)
问题描述
使用部件编号创建新日期
对象时,我得到的值在我放置的值之前正好一个月在'月'。
When creating a new Date
object using numbers for the parts, the value I get back is exactly one month ahead of the value I put in for 'month'.
new Date(2012, 05, 17, 00, 00, 00)
Sun Jun 17 2012 00:00:00 GMT+0800 (HKT) // june?!
然而,完全相同字符串的正常解析会返回正确的时间:
However, a normal parse of exactly the same string returns the correct time:
new Date("2012-05-17 00:00:00")
Thu May 17 2012 00:00:00 GMT+0800 (HKT)
我在ie / ff / chrome中得到相同的结果。删除小时/分钟/秒没有任何效果。我可以通过在设置月份之前减去一个来解决它,但我只是改为将日期写为字符串。
I get the same result in ie/ff/chrome. Removing hours/min/seconds doesn't have any effect. I can work around it by subtracting one before setting the month, but instead I just switched to writing out my date as a string.
编辑:
字符串解析在IE中不起作用。我不知道我做了什么,但我发誓我做了那件事。多数民众赞成。为什么我首先避免它。我现在转而使用moment.js.
啊,现在我明白了。就像常规的java日期一样,我很少编写代码,甚至很少,甚至总是用库(joda等)。无论如何,这是多么可怕的想法。以下是双关语问题:为什么Java日历中的1月0月?
Ah, now I get it. Just like regular java dates, which I don't code in except rarely, and even then always with a library (joda, etc). What a terrible idea anyway. Here is skeets take on the question: Why is January month 0 in Java Calendar?
为什么会这样?
推荐答案
程序员从0开始计数。所以月份由0(1月)-11(12月)代表。
Programmers start counting from 0. So months are represented by 0(Jan)-11(Dec).
天不遵守此规则的原因是不要将作者与30/31个月的差异混淆。
The reason days don't follow this rule is to not confuse authors with 30/31 month differences.
From MDN:
表示月份的整数值,从1月份的0开始到12月份的
11。
month
Integer value representing the month, beginning with 0 for January to 11 for December.
这篇关于用数字创建日期(新日期(2012年,03年,...)给出错误的月份(+1)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!