JS用Date.gettime("yyy-MM-dd hh:mm:ss")解析时间格式,IE8以下的环境下出现NaN, safari浏览器出现NaN
解法 :
1 function time(){ 2 3 var timeBegin = ''2018-09-18 12:00:00" 4 5 var startTime =timeBegin.replace(/\-/g, "/"); // 需要将字符串日期中的 ‘-’ 替换成 ‘/’ , 6 return new Date(startTime).getTime();// 这里得的就是时间戳,不会是NaN 7 8 function test() { 9 var dateStr = "02/01/2015" 10 var date = Date.parse(dateStr ) 11 12 alert(date ); 13 }
js的Date.parse()方法和getTime()的陷阱
getTime()和Date.parse()方法都是返回某个时间到1970年1月1日0:00的时间戳,但是下面代码结果却是 1970年1月1日08:00 开始,这样就相差八个小时
function startTime() { let date = new Date, year = date.getFullYear(), month = date.getMonth() + 1, day = date.getDate(); // 因为当年月日中间是 ‘-’ 短横线的时候,它的解析是用UTC 时区处理,而不是用本地时区处理的,因此相差八个小时,就成了这个时间点到1970年1月1日08:00的毫秒数。 // 解决办法就是将日期中的短横线替换成 ‘/’ , // getTime()和Date.parse()方法 都会有相同的情况 return Date.parse(year + '-' + month + '-' + day) ; }