微信小程序 倒計時


這兩天在看微信小程序,參考了網上的資料,做了一個倒計時的練習,記錄如下。

本文作者:羅兵

原地址: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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM