微信小程序 倒计时

这两天在看微信小程序,参考了网上的资料,做了一个倒计时的练习,记录如下。

本文作者:罗兵

原地址:https://www.cnblogs.com/hhh5460/p/9981064.html

0、效果

1、视图

<!-- index.wxml -->

<view class='datetimeTo'>距离:<text style='color:blue'>{{datetimeTo}}</text></view>
<view class='timeLeft'>还有:<text style='color:red'>{{timeLeft}}</text></view>

 

2、逻辑

//index.js

const util = require('../../utils/util.js')

Page({
  data: {
    datetimeTo: "2019/01/01 10:30:00 GMT+0800", // 秒杀开始时间
    timeLeft: ""    // 剩下的时间(天时分秒)
  },
  onShow: function () {
    this.data.timer = setInterval(() =>{ //注意箭头函数!!
      this.setData({
        timeLeft: util.getTimeLeft(this.data.datetimeTo)//使用了util.getTimeLeft
      });
      if (this.data.timeLeft == "0天0时0分0秒") {
        clearInterval(this.data.timer);
      }
    }, 1000);
  }
});

 

3、工具

//util.js

//取倒计时(天时分秒)
function getTimeLeft(datetimeTo){
  // 计算目标与现在时间差(毫秒)
  let time1 = new Date(datetimeTo).getTime();
  let time2 = new Date().getTime();
  let mss = time1 - time2;
  
  // 将时间差(毫秒)格式为:天时分秒
  let days = parseInt(mss / (1000 * 60 * 60 * 24));
  let hours = parseInt((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  let minutes = parseInt((mss % (1000 * 60 * 60)) / (1000 * 60));
  let seconds = parseInt((mss % (1000 * 60)) / 1000);
  
  return days + "天" + hours + "时" + minutes + "分" + seconds + "秒"
}

module.exports = {
  getTimeLeft: getTimeLeft
}

 4、参考

微信小程序定时器:https://www.cnblogs.com/baqiphp/p/6145450.html

js毫秒化天时分秒:https://www.cnblogs.com/Byme/p/7844695.html

posted @ 2018-11-19 00:44  罗兵  阅读(12876)  评论(0编辑  收藏  举报