简单记录一下吧!!!
wxml:
<view class="countdown">
<view class="countdown-title">距离活动结束还有:</view>
<view class="countdown-timer">
{{ days }}天 {{ hours }}时 {{ minutes }}分 {{ seconds }}秒
</view>
</view>
wxss:
.countdown {
text-align: center;
margin: 20px;
background-color: #f5f5f5;
padding: 15px;
border-radius: 10px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.countdown-title {
font-size: 18px;
font-weight: bold;
color: #333;
margin-bottom: 10px;
}
.countdown-timer {
font-size: 24px;
color: #e44d26; /* 橙色字体 */
}
js:
Page({
data: {
days: 0,
hours: 0,
minutes: 0,
seconds: 0,
endTime: '2024/03/01 00:00:00', // 使用兼容的日期字符串格式
},
onLoad: function () {
this.countDown();
},
countDown: function () {
const that = this;
setInterval(function () {
const nowTime = new Date().getTime();
const endTime = new Date(that.data.endTime.replace(/-/g, '/')).getTime(); // 替换日期格式并转换为时间戳
let distance = endTime - nowTime;
const days = Math.floor(distance / (1000 * 60 * 60 * 24));
const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((distance % (1000 * 60)) / 1000);
that.setData({
days: that.formatTime(days),
hours: that.formatTime(hours),
minutes: that.formatTime(minutes),
seconds: that.formatTime(seconds),
});
}, 1000);
},
formatTime: function (time) {
return time < 10 ? '0' + time : time;
}
});
备注:
endTime之所以使用 '2024/03/01 00:00:00'格式,是因为使用new Date('2024-03-01 00:00:00').getTime()处理时间时,会出现以下警告: