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

上一篇:微博爬虫,python微博用户主页小姐姐图片内容采集爬虫


下一篇:【WebMisCentral WMC】基于Extjs 4.2x的企业级用户授权认证中心系统(SSO+AM+SM),多租户SAAS应用