欢迎各位兄弟 发布技术文章
这里的技术是共享的
有如下的js代码片段
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | function toDate(str) { if (str.length==10&&str.indexOf( "-" )>0){ var yy = str.substring(0,4); var mm = str.substring(5,7); var dd = str.substring(8,10); var date = new Date(); date.setFullYear(yy); date.setMonth(mm-1); date.setDate(dd); date.setHours(1); date.setMinutes(0); date.setSeconds(0); date.setMilliseconds(0); return date; } return false ; } |
功能是将传入参数转换为日期,格式也挺固定,为"yyyy-MM-dd",使用了一段时间之后,发现一个问题。
传入日期为"2014-02-11",返回日期为2014-03-11,正确日期应该是2014-02-11,奇数没问题,只要传入月份是偶数,则必定出问题。
查看Date类的API的说明是这样的:
不知道是JS的BUG还是哪的问题,解决方案为将new Date()改为new Date("2000-0-1"),总之构造函数不能为空。
修改后的代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | function toDate(str) { if (str.length==10&&str.indexOf( "-" )>0){ var yy = str.substring(0,4); var mm = str.substring(5,7); var dd = str.substring(8,10); var date = new Date( "2000-0-1" ); date.setFullYear(yy); date.setMonth(mm-1); date.setDate(dd); date.setHours(1); date.setMinutes(0); date.setSeconds(0); date.setMilliseconds(0); return date; } return false ; } |
还有个问题,计算时间时不能简单的用getTime() + offset,要算上时差,不然日期也会出错。
来自 http://blog.csdn.net/huaishuming/article/details/40658641