微信小程序实现活动倒计时显示

本文详细介绍了如何在微信小程序中使用WXML、WXSS和JavaScript实现一个倒计时功能,以及为何选择特定日期格式以避免警告。
摘要由CSDN通过智能技术生成

简单记录一下吧!!!

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()处理时间时,会出现以下警告:

  • 9
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值