今天早上我注意到了JavaScript setFullYear方法的一个特殊问题.
使用这样的方法时:
d.setFullYear(2012,2,8);
返回正确的值:
Thu Mar 08 2012 10:30:04 GMT+0000 (GMT Standard Time)
但是,如果我使用parseInt方法返回整数,则返回的日期不正确:
d.setFullYear(parseInt("2012"),parseInt("02"),parseInt("08"));
收益:
Wed Feb 29 2012 10:31:30 GMT+0000 (GMT Standard Time)
看来parseInt方法返回的值不正确,但是当我测试它时:
然后返回正确的值(2)
一个工作小提琴在这里:http://jsfiddle.net/rXByJ/
问题在于parseInt还是setFullYear?
最佳答案
问题是parseInt(’08’)为0.这有效:
d.setFullYear(parseInt("2012"),8);
Both parseInt(’08’) and parseInt(’09’) return zero because the@H_502_58@ function tries to determine the correct base for the numerical system@H_502_58@ used. In Javascript numbers starting with zero are considered octal@H_502_58@ and there’s no 08 or 09 in octal,hence the problem.
http://www.ventanazul.com/webzine/articles/issues-parseint-javascript
解决方案是使用第二个参数:
parseInt('08',10)
要么
Number('08')
另见How do I work around JavaScript’s parseInt octal behavior?