JS獲取當前時間戳的方法-JavaScript 獲取當前毫秒時間戳有如下三種方法: var timestamp =Date.parse(new Date()); 結果:1280977330000 //不推薦; 毫秒改爲了000顯示 var timestamp =(new Date()).valueOf(); 結果:1280977330748 //推薦; var timestamp=new Date().getTime(); 結果:1280977330748 //推薦; js中單獨調用new Date(); 顯示這種格式 Mar 31 10:10:43 UTC+0800 2012 可是用new Date() 參與計算會自動轉換爲從1970.1.1開始的毫秒數
function timestampFormat( timestamp ) { var curTimestamp = new Date().getTime(); //當前時間戳 // console.log(curTimestamp); var Diff = curTimestamp - timestamp; // 參數時間戳與當前時間戳相差秒數 var curDate = new Date( curTimestamp); // 當前時間日期對象 var tmDate = new Date( timestamp); // 參數時間戳轉換成的日期對象 var Y = tmDate.getFullYear(), m = tmDate.getMonth() + 1, d = tmDate.getDate(); var H = tmDate.getHours(), i = tmDate.getMinutes(), s = tmDate.getSeconds(); if ( Diff < 60*1000 ) { // 一分鐘之內 return "剛剛"; } else if( Diff < 3600*1000 ) { // 一小時前以內 return Math.floor( Diff / (60*1000 )) + "分鐘前"; } else if ( curDate.getFullYear() == Y && curDate.getMonth()+1 == m && curDate.getDate() == d ) { return Math.floor( Diff / (60*60*1000 )) + "小時前"; } else { var newDate = new Date( (curTimestamp - 86400*1000)); // 參數中的時間戳加一天轉換成的日期對象 if ( newDate.getFullYear() == Y && newDate.getMonth()+1 == m && newDate.getDate() == d ) { return '一天前'; } else if (Diff>86400*1000*2){ return new Date(timestamp); } } } console.log(timestampFormat(1557930299182)) //2012年01月10日 12:46 console.log(timestampFormat(1557930200000)) //剛剛 console.log(timestampFormat(Date.parse('2016-10-11 15:10:10'))) //16分鐘前 console.log(timestampFormat(Date.parse('2016-10-11 10:10:10')))//今天10:10 console.log(timestampFormat(Date.parse('2016-10-10 10:10:10'))) //昨天10:10 console.log(timestampFormat(Date.parse('2016-02-10 10:10:10'))) //02月10日 10:10 console.log(timestampFormat(Date.parse('2012-10-10 10:10:10'))) //2012年10月10日 10:10