• 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;
     }
    })

  • 相关阅读:
    npmcnpmyarn yarn 关于源和代理的问题
    react : umi 引入 antd 踩坑
    Ant Design Pro 学习笔记:数据流向
    dva + umi 学习笔记
    简单分析 ztree 源码
    X-Tag实战:给博客加一个隐藏侧栏的功能
    javascript中var,let,const的区别
    linq 延迟执行带来的困扰
    如何实现能像windows 窗体一样改变大小的控件 Silverlight
    一个循环递归遍历问题
  • 原文地址:https://www.cnblogs.com/yangjing1314/p/8583642.html
Copyright © 2020-2023  润新知