js 倒计时 时间戳

功能:传入一个截止时间(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

原文地址:https://www.cnblogs.com/hamsterPP/p/5091386.html