Chrome和Firefox之间的时间戳转换差异 [英] Timestamp conversion difference between Chrome and Firefox
问题描述
new Date(parseInt ('2012'),parseInt('09') - 1,parseInt('30'))getTime()/ 1000
当我执行 Chrome 时,我得到:
1348956000
当我在 Firefox 中执行它时,我得到:
1325199600
问题:这里有什么问题?
对于 parseInt('09' )
:
- Chrome 24似乎返回 9
- FireFox 18似乎将该号码视为 octal 因此返回 0 (0被解析但9不是)
从 parseInt
文档:
虽然ECMAScript 3不鼓励,但是许多实现解释了一个
数字字符串,以前导0开头为八进制。
[...]
函数parseInt不再是
的ECMAScript 5规范允许实现将以0字符
开头的字符串视为八进制值。
[...]
由于许多实现没有采用这种行为截至2011年,
并且因为旧浏览器必须被支持,所以总是指定一个基数。
解决方案:修改代码并明确指定基数参数:
new Date(parseInt('2012' ,10),parseInt('09',10)-1,parseInt('30',10))getTime()/ 1000
pre>
// 1348945200
I'm currently running into trouble when dealing with timestamps. I am debugging the following, exactly same code in Chrome 24.0.1312.56 m and Firefox 18.0.1 console:
new Date(parseInt('2012'), parseInt('09') - 1, parseInt('30')).getTime()/1000
When I execute it in Chrome I get:
1348956000
And when I execute it in Firefox I get:
1325199600
Question: What is the problem here?
解决方案For
parseInt('09')
:
- Chrome 24 seems to return 9
- FireFox 18 seems to treat the number as octal therefore returns 0 (the 0 is parsed but 9 is not)
Quote from parseInt
documentation:
Although discouraged by ECMAScript 3, many implementations interpret a numeric string beginning with a leading 0 as octal.
[...]
The ECMAScript 5 specification of the function parseInt no longer allows implementations to treat Strings beginning with a 0 character as octal values.
[...]
Since many implementations have not adopted this behavior as of 2011, and because older browsers must be supported, always specify a radix.
Solution: revise your code and explicitly specify the radix parameter:
new Date(parseInt('2012', 10), parseInt('09', 10) - 1, parseInt('30', 10)).getTime()/1000
// 1348945200
这篇关于Chrome和Firefox之间的时间戳转换差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!