zoukankan      html  css  js  c++  java
  • js根据服务端返回的时间倒计时

    使用服务端与本地的时间差进行计算


    $(function(){
    // 倒计时
    var _ordertimer = null;
    var data =new Date();
    var txt = $('.js_time_txt');
    var buyTime = '2018/03/28 10:30:00'; //开抢时间
    var nowTime = '2018/03/16 17:00:00'; //接口返回当前时间

    var dateDiff = new Date(nowTime) - new Date(getnow()); //请求时间戳与本地时间戳
    if(dateDiff < 0 ){
    dateDiff = Math.abs(dateDiff);
    }

    if(new Date(nowTime) > new Date(buyTime)){
    $('.time-range').hide(); //已开枪
    return;
    } else{
    leftTimer(buyTime);
    _ordertimer = setInterval(function(){leftTimer(buyTime)}, 1000);
    }

    // 获取当前时间 xxxx/xx/xx 00:00:00
    function getnow(){
    var year = data.getFullYear();
    var month = parseInt(data.getMonth()+1) >= 10 ? parseInt(data.getMonth()+1) : '0' + parseInt(data.getMonth()+1);
    var day = data.getDate();
    var hours = data.getHours();
    var minutes = data.getMinutes();
    var seconds = data.getSeconds();
    var now = year +'/'+ month +'/'+ day +' '+ hours +':'+ minutes +':'+ seconds;
    return now;
    }

    function leftTimer(enddate) {

    var leftTime = (new Date(enddate)) - new Date + dateDiff;

      var days = parseInt(leftTime / 1000 / 60 / 60 / 24, 10); //计算剩余的天数
      var hours = parseInt(leftTime / 1000 / 60 / 60 % 24, 10); //计算剩余的小时
      var minutes = parseInt(leftTime / 1000 / 60 % 60, 10);//计算剩余的分钟
      var seconds = parseInt(leftTime / 1000 % 60, 10);//计算剩余的秒数
      days = checkTime(days);
      hours = checkTime(hours);
      minutes = checkTime(minutes);
      seconds = checkTime(seconds);

      if (days >= 0 || hours >= 0 || minutes >= 0 || seconds >= 0)
    txt.html(days + "天" + hours + "小时" + minutes + "分" + seconds + "秒");
      if (days <= 0 && hours <= 0 && minutes <= 0 && seconds <= 0) {
      window.clearInterval(_ordertimer);
      _ordertimer = null;
      }
     }

     function checkTime(i) { //将0-9的数字前面加上0,例1变为01
      if (i < 10) {
      i = "0" + i;
      }
      return i;
     }
    })

  • 相关阅读:
    进程通信
    我(撞破南墙)的部分文章索引
    我(撞破南墙)参加"博客无双"的文章以及参加的原因(2010年12月05日update)
    MVC3RAZOR尝鲜2细说实用的WebGrid
    MVC3RAZOR尝鲜之漂亮的chart图表
    ASP.NETMVC3RC的一些新特性 (2010.11.9发布版)
    MVC3RAZOR尝鲜1
    Silverlight应用开发2webcam自拍保存和"录像"
    C#功能派的进阶你该思考的一些事1
    MVC3Razor简单文件操作
  • 原文地址:https://www.cnblogs.com/yangjing1314/p/8583642.html
Copyright © 2011-2022 走看看