用JS实现倒计时(日期字符串作为参数)

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>JS实现倒计时</title>
    <style>
        *{ margin:0; padding:0; list-style:none;}
        body{ font-size:18px; text-align:center;}
        .time{ height:30px; padding:200px;}
    </style>
</head>
<body>
<div class="time">
    <span id="showInterval"></span>
</div>
<script>

    function getDistanceTime(time,showInterval){
        var endTime= new Date(Date.parse(time.replace(/-/g, "/")));/*replace将时间字符串中所有的'-'替换成'/',parse将时间格式的字符串转换成毫秒*/
        var nowTime = new Date();
        var distance =endTime.getTime() - nowTime.getTime();/*getTime把一个date对象转换成毫秒*/

        var day = 0;
        var hour = 0;
        var minute = 0;
        var second = 0;

        if(distance >= 0){
            day = Math.floor(distance/1000/60/60/24);
            hour = Math.floor(distance/1000/60/60%24);
            minute = Math.floor(distance/1000/60%60);
            second = Math.floor(distance/1000%60);
        }else{
            alert("目标日期小于当前日期!")
        }

        document.getElementById(showInterval).innerHTML = day + "" +  hour + "" + minute + "" + second + "";
    }
//    setInterval(function(){getDistanceTime('2016/05/19 12:00:00','showInterval');},0);
    setInterval(function(){getDistanceTime('2017-05-19 12:00:00','showInterval');},0);
</script>

</body>
</html>

传入的日期参数格式,也可以是'2017/05/19 12:00:00'

效果如下:

posted @ 2016-05-18 11:13  木西梧  阅读(5062)  评论(0编辑  收藏  举报