小程序活动倒计时及时间格式化

55 篇文章 3 订阅
40 篇文章 1 订阅

在这里插入图片描述

距离开始大于1天,显示开始时间,未开始(一天内)和 进行中展示倒计时

	<view class="state-time">
	  //state 0 距离开始大于1天  1 未开始(一天内) 2 进行中  3 已结束
      <block wx:if="{{state==1||state==2}}">
        <image class="state" src="/images/new-state{{state}}.png"/>
        <!-- 倒计时 -->
        <wxs src="../../wxs/ac-new.wxs" module="account_time" />
        <view class="time center">
          <view class="time-item center black">{{account_time.accountTime(time).h}}</view>
          <image class="colon" src="/images/new-colon.png" />
          <view class="time-item center black">{{account_time.accountTime(time).m}}</view>
          <image class="colon" src="/images/new-colon.png" />
          <view class="time-item center black">{{account_time.accountTime(time).s}}</view>
        </view>
      </block>
      
      <block wx:if="{{state==0}}">
        <wxs src="../../wxs/date.wxs" module="wxs_time" />
        <view class="white size-36 center">预售时间</view>
        <view class="white size-36 center">{{wxs_time.format(initdata.start_time,'MM月dd日 hh时mm分')}}</view>
      </block>
    </view>

wxs文件 1、实时传入倒计时时间差, 处理成时分秒展示在页面 2、传入时间戳,格式化时间

// ac-new.wxs 处理页面倒计时显示
/**
 *
 * @param time -倒计时时长
 */
var accountTime = function (time) {
  var obj = {}
  // 计算多少天,多少小时(24小时以内)
  // var d = parseInt((time / (60 * 60)) / 24)
  // var h = parseInt((time / (60 * 60)) % 24)
  // 不计算天,最大以小时来记
  var h = parseInt (time / (60 * 60))
  var m = parseInt((time / 60) % 60)
  var s = parseInt(time % 60)
  obj.h = addZero(h)
  obj.m = addZero(m)
  obj.s = addZero(s)
  return obj
}
function addZero(i) {
  return i < 10 ? '0' + i : i + ''
}
module.exports = {
  accountTime: accountTime,
}

// date.wxs 实例时间戳格式化
/* eslint-disable no-undef */
module.exports = {
  format: function dateFormat(timestamp, format) {
    if (!format) {
      format = 'yyyy-MM-dd hh:mm:ss'
    }
    timestamp = parseInt(timestamp * 1000)
    var realDate = getDate(timestamp)
    function timeFormat(num) {
      return num < 10 ? '0' + num : num
    }
    var date = [
      ['M+', timeFormat(realDate.getMonth() + 1)],
      ['d+', timeFormat(realDate.getDate())],
      ['h+', timeFormat(realDate.getHours())],
      ['m+', timeFormat(realDate.getMinutes())],
      ['s+', timeFormat(realDate.getSeconds())],
      ['q+', Math.floor((realDate.getMonth() + 3) / 3)],
      ['S+', realDate.getMilliseconds()],
    ]
    var regYear = getRegExp('(y+)', 'i')
    var reg1 = regYear.exec(format)
    if (reg1) {
      format = format.replace(
        reg1[1],
        (realDate.getFullYear() + '').substring(4 - reg1[1].length)
      )
    }
    for (var i = 0; i < date.length; i++) {
      var k = date[i][0]
      var v = date[i][1]
      var reg2 = getRegExp('(' + k + ')').exec(format)
      if (reg2) {
        format = format.replace(
          reg2[1],
          reg2[1].length == 1 ? v : ('00' + v).substring(('' + v).length)
        )
      }
    }
    return format
  },
}

js:调取接口后,定时器每秒获取当前时间戳,倒计时结束时间减去当前时间,得到倒计时的时间差,当时间差小于等于0,清除定时器,改变活动状态

	import NP from 'number-precision'
	import {
	  http,
	  loginRedirect,
	  unescapeHTML,
	  actStatus,
	} from '../../../utils/index'
	
		
	async onLoad() {
      await this.init()
      if (this.data.state == 1 || this.data.state == 2) {
        timerid = setInterval(() => {
          let now = new Date().getTime() / 1000
          this.setData({
            time: NP.minus(
              this.data.state == 1
                ? this.data.start_time * 1
                : this.data.end_time * 1,
              now
            ),
          })
          if (this.data.state == 2 && this.data.time <= 0) {
            clearInterval(timerid)
            this.setData({
              state: 3,
            })
          } else if (this.data.state == 1 && this.data.time <= 0) {
            clearInterval(timerid)
            this.setData({
              state: 2,
            })
          }
        }, 1000)
      }
    },
    async init() {
      try {
        const { data } = await http.get('/activity/numans/activityDetail', {
          params: {
            activity_id: this.data.act_id,
          },
        })
        this.setData({
          activity_rule: unescapeHTML(data.activity_rule),
          start_time: data.start_time,
          end_time: data.end_time,
          state: actStatus(data.start_time, data.end_time),
          list: data.goods_list,
          is_new_user: data.is_new_user == 1 ? true : false,
        })
      } catch (error) {}
    },

公共方法utils,获取活动状态

/**
 * 新人专享活动 0 距离开始大于1天  1 未开始(24小时内)  2 进行中  3 已结束
 * @param start -开始时间戳
 * @param end -结束时间戳
 */
export const actStatus = (start, end) => {
  let now = new Date().getTime() / 1000
  start = start * 1
  end = end * 1
  // 未开始状态
  if (now < start) {
    if (start - now > 86400) {
      return 0
    } else {
      return 1
    }
  } else if (now >= end) {
    return 3
  } else {
    return 2
  }
}

页面离开,清除倒计时,返回执行onUnload,所以在全局定义定时器,在方法里赋值。去下一个页面执行onHide,无需清除定时器,因为会返回来,就算不返回来,过一段时间页面也会自动销毁

在这里插入图片描述

    onUnload() {
      clearInterval(timerid)
    },
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小曲曲

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值