uniapp微信小程序實現倒計時功能


1.實現的效果:

 

 2.js

tuan(index) {
				this.house_id = index;
				var that = this;
				var wechat = uni.getStorageSync('wechat');
				that.wechat = wechat;

				// 初始化請求
				uni.request({
					url: that.COMMON.ApiUrl + "/api/MakeGroup/index",
					data: {
						openid: wechat.openid,
						house_id: index
					},
					success: (res) => {
						console.log('拼團', res)
						if (res.data.group['end_time']) {
							var bend = this.getdate(res.data.group['end_time']);
						}
						var utils = require('../../utils/utils.js');
						this.timer = setInterval(() => { //注意箭頭函數!!
							that.infotime = utils.getTimeLeft(bend) //使用了util.getTimeLeft
							if (this.infotime == "0天0時0分0秒") {
								clearInterval(this.data.timer);
							}
						}, 1000);
						that.houses = res.data.houses;
						that.group = res.data.group;
						that.infoHtml = graceRichText.format(res.data.group['info']); //內容
					},
					fail: function() {
						uni.showToast({
							title: '接口獲取失敗',
							icon: 'none',
							duration: 500
						});
					}
				})
			},

 

getdate(value) {
if (!value) return '';
value = parseInt(value) * 1000
var now = new Date(value);
var year = now.getFullYear();
var month = now.getMonth() + 1;
if (month < 10) {
month = '0' + month
}
var date = now.getDate();
if (date < 10) {
date = '0' + date
}
return year + "-" + month + "-" + date
},

 

3.utils.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
}

  

  


免責聲明!

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



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