微信小程序—动态显示项目倒计时(格式:6天6小时58分钟39秒)

1、展示的效果如下

2、wxml代码:

<!--倒计时  -->
<text wx:if="{{clock!=''}}">仅剩{{clock}}</text>
<text wx:if="{{clock==''}}">已经截止</text></text>

3、js代码:

在拼团项目中获取到活动结束时间的格式为一下格式

因该格式无法正常计算时长,所进行了格式转换new Date(that.data.collage.collage_end).getTime()

// 倒计时
function countdown(that) {
  var EndTime = new Date(that.data.collage.collage_end).getTime() || [];
  // console.log(EndTime);
  var NowTime = new Date().getTime();
  var total_micro_second = EndTime - NowTime || [];   //单位毫秒
  if (total_micro_second < 0) {
    // console.log('时间初始化小于0,活动已结束状态');
    total_micro_second = 1;     //单位毫秒 ------  WHY?
  }
  // console.log('剩余时间:' + total_micro_second);
  // 渲染倒计时时钟
  that.setData({
    clock: dateformat(total_micro_second)   //若已结束,此处输出'0天0小时0分钟0秒'
  });
  if (total_micro_second <= 0) {
    that.setData({
      clock: "已经截止"
    });
    return;
  }
  setTimeout(function () {
    total_micro_second -= 1000;
    countdown(that);
  }
    , 1000)
}

// 时间格式化输出,如11天03小时25分钟19秒  每1s都会调用一次
function dateformat(micro_second) {
  // 总秒数
  var second = Math.floor(micro_second / 1000);
  // 天数
  var day = Math.floor(second / 3600 / 24);
  // 小时
  var hr = Math.floor(second / 3600 % 24);
  // 分钟
  var min = Math.floor(second / 60 % 60);
  // 秒
  var sec = Math.floor(second % 60);
  return day + "天" + hr + "小时" + min + "分钟" + sec + "秒";
}
Page({
    onLoad: function(options) {
        wx.request({
            success: function(request) {
                // 倒计时(获取结束时间后再进行倒计时方法调用)
                countdown(that);
            }
        })
    }   
})

猜你喜欢

转载自blog.csdn.net/aaaaaayuan/article/details/81389894
今日推荐