View Post
js时间字符串转换成毫秒
将“yyyy-MM-dd HH:mm:ss”字符串转换成Date
在谷歌浏览器chrome 下
$(\'detail\').value = new Date(\'2013-04-15 15:53:40\').getTime();可以直接转换成毫秒,但是在IE6下是不能的
所以就有了下面这个转换的例子了,兼容ie6
1 <html> 2 <head> 3 <script type="text/javascript"> 4 function $(id){ 5 return document.getElementById(id); 6 } 7 8 String.prototype.trim = function () { 9 return this.replace(/(^\s*)|(\s*$)/g, ""); 10 }; 11 12 // 将“yyyy-MM-dd HH:mm:ss”字符串转换成Date 13 //把“yyyy-MM-dd”字符串转换成Date,不兼容chrome 14 function parseDate(dateString) 15 { 16 var dateReg = /^([1-9]\d{3})-(0?[1-9]|1[0-2])-(0?[1-9]|[12]\d|3[01])( ((0?|1)\d|2[0-3]):((0?|[1-5])\d):((0?|[1-5])\d))?$/; 17 if (!dateReg.test(dateString)) 18 { 19 return null; 20 } 21 var childgroups = dateString.match(dateReg); 22 var execFuncs = ["", "setFullYear", "setMonth", "setDate", "", "setHours", "", "setMinutes", "", "setSeconds", ""]; 23 var date = new Date(0); 24 for (var i = 0; i < childgroups.length; i++) 25 { 26 if (execFuncs[i] != "" && childgroups[i] != "") 27 { 28 var num = Number(childgroups[i]); 29 if (execFuncs[i] == "setMonth") 30 { 31 num -= 1; 32 } 33 date[execFuncs[i]](num); 34 } 35 } 36 return date; 37 } 38 39 function foo() 40 { 41 42 $(\'detail\').value = "2013-04-15 15:53:40转换成毫秒:"+ parseDate($(\'detail\').value.trim()).getTime(); 43 44 } 45 </script> 46 </head> 47 <body> 48 49 <div height="100px"> 50 <fieldset> 51 <legend><strong>时间转换</strong></legend> 52 <input type="text" id="detail" name="qwe" style="width: 400px" value="2013-04-15 15:53:40" > 53 <input type="button" id="roViewType12" name="buttonname" value="获取选中的信息" onclick="foo()"> 54 55 </fieldset> 56 </div> 57 58 </body> 59 </html>