let date = new Date('2014-04-23 18:55:49:123'); // 有三種方式獲取 let time1 = date.getTime(); let time2 = date.valueOf(); lettime3 = Date.parse(date); console.log(time1);//1398250549123 console.log(time2);//1398250549123 console.log(time3);//1398250549000
以上三種獲取方式的區別:
第一、第二種:會精確到毫秒
第三種:只能精確到秒,毫秒用000替代
以上三個輸出結果可觀察其區別
注意:獲取到的時間戳除以1000就可獲得Unix時間戳,就可傳值給后台得到。
將時間戳轉換成日期格式:
function timestampToTime(timestamp) { var date = new Date(timestamp * 1000);//時間戳為10位需*1000,時間戳為13位的話不需乘1000 Y = date.getFullYear() + '-'; M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-'; D = date.getDate() + ' '; h = date.getHours() + ':'; m = date.getMinutes() + ':'; s = date.getSeconds(); return Y+M+D+h+m+s; } timestampToTime(1403058804); console.log(timestampToTime(1403058804));//2014-06-18 10:33:24