微信小程式—動態顯示專案倒計時(格式:6天6小時58分鐘39秒)
阿新 • • 發佈:2019-01-09
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); } }) } })