功能:傳入一個截止時間(unix時間戳),顯示倒計時
因為unix時間戳,並不等於js 的new Date().getTime()得到的那一串毫秒數,所以要在JS中使用unix時間戳,必須先轉換一下unix時間戳;
--------------------------------------------------------------------------------------------------
js得到unix時間戳:
js code
Math.round(new Date().getTime()/1000);//javascript 得到當前時間的unix時間戳
unix時間戳轉換成js中可用的格式:
js code:
var timestamp = new Date(timestamp * 1000);
/******如果需要得到普通時間:
*var commonTime = timestamp .toLocaleString();
*console.log(commonTime);//打印結果如下:2015年12月31日 GMT+818:00:00
**********/
一個比較完整的傳入unix時間戳參數,得到倒計時的函數:
js code:
function getCountDown(timestamp){ setInterval(function(){ var nowTime = new Date(); var endTime = new Date(timestamp * 1000); var t = endTime.getTime() - nowTime.getTime(); // var d=Math.floor(t/1000/60/60/24); var hour=Math.floor(t/1000/60/60%24); var min=Math.floor(t/1000/60%60); var sec=Math.floor(t/1000%60); if (hour < 10) { hour = "0" + hour; } if (min < 10) { min = "0" + min; } if (sec < 10) { sec = "0" + sec; } var countDownTime = hour + ":" + min + ":" + sec; $("#countDown1").html(countDownTime); },1000); }
//調用函數:
getCountDown(1451556000);//時間戳可以去百度一下,這里的時間是2015年12月31日18:00:00
html code
<p id="countDown1"></p>
結果:這個p標簽應該會動態的顯示當前到18:00的每秒倒計時,例如:04:56:08