日期和unix时间之间的时间,以及计时器倒计时

时间:2012-07-08 18:32:32

标签: php javascript date timer unix-timestamp

由于我的标题是sais,我想制作一个计时器,用于计算当前时间的unix时间和js中的日期(包括小时分钟和秒数)之间的时间。

我不知道如何做到这一点你能在这里给我一些帮助吗?

3 个答案:

答案 0 :(得分:1)

  var now = new Date();
  var date = new Date(2012, 7, 9);
  var diff = new Date(date - now);

  var res = '';
  res += diff.getHours()   + 'h ';
  res += diff.getMinutes() + 'min ';
  res += diff.getSeconds() + 's';

See it in action on JS Bin

答案 1 :(得分:1)

var timestamp = new Date(2012,6,8,13,54,52).getTime()-new Date().getTime(); 
// 0 based month
var tid = setInterval(
  function() {
    if (timestamp<=0) clearIntervaltid);
    document.getElementById("timeContainer").innerHTML=new Date(timestamp-=1000);
  },1000);

答案 2 :(得分:0)

此倒计时也处理负数时间(达到倒计时)。

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript">
        var zeroDate_ms = Date.parse("8 Jul 2012 22:41:00 GMT+2");
        window.setInterval("countdown()", 1000);
        function countdown() {
            var now_ms = Number(new Date());
            var sign = (zeroDate_ms < now_ms) ? "-":"";
            var diff_s = Math.floor(Math.abs(zeroDate_ms - now_ms)/1000);
            var diff_h = Math.floor(diff_s / 3600/*1000*60*60*/);
            diff_s -= (diff_h * 3600);
            var diff_m = Math.floor(diff_s / 60/*1000*60*/);
            diff_s -= (diff_m * 60)
            var h = String(diff_h);
            var m = ("0"+String(diff_m)).substr(-2);
            var s = ("0"+String(diff_s)).substr(-2);
            document.getElementById("countdown").innerHTML=sign+h+":"+m+":"+s
        }

    </script>
</head>
<body>
    <div id="countdown"></div>
</body>
</html>