解法 :
瀏覽器
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 }
getTime()和Date.parse()方法都是返回某個時間到1970年1月1日0:00的時間戳,可是下面代碼結果倒是 1970年1月1日08:00 開始,這樣就相差八個小時spa
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) ; }