前序
-
之前写一个 单个倒计时,不完善 不完善的倒计时
-
新需求有多个活动的倒计时
-
接收如下类似这样数据
2020-05-14 14:30:30 -》 01天23时12分01秒
[{
title: '...',
content: '...',
img: '...',
activeDeta: '2020-05-14 14:30:30',
countdown: null
},{
title: '...',
content: '...',
img: '...',
activeDeta: '2020-05-15 16:23:20',
countdown: null
}]
- 返回如下数据
[{
title: '...',
content: '...',
img: '...',
activeDeta: '2020-05-15 16:23:20',
countdown: {
day: '10',
hour: '01',
minutes: '20',
seconds: '10'
}
}]
多个倒计时
思路
-
1,遍历数组获取日期,解析日期为时间戳,减去当前时间戳/1000,获取距离活动日期秒数
-
2,通过之前util.js 里的formatStamp,获取天时分秒,并赋给数组中的countdown
代码
import { formatStamp } from '../../util.js'
getTimes () {
let timer
let that = this
// setInterval function
countdown () {
let allStamp = 0
for (var i = 0; i < araryObject.length; i++) {
diffTime = (Date.parse(araryObject[i].activeDeta) - Date.now()) / 1000
diffTime--
if (diffTime <= 0) { // 这一步防止倒计时出现负数
diffTime = 0
}
// 当diffTime相加等于0时,清理定时器
allStamp += diffTime
if (allStamp <= 0) {
clearInterval(timer)
}
let combination = 'araryObject[' + i + '].countdown'
that.setData({
[combination]: formatStamp(diffTime, true)
})
}
}
timer = setInterval(countdown, 1000)
}
提示:formatStamp第二个参数true:包含天(01天1时01分01秒),false:将天转小时(25时01分01秒)
util.js
// 格式时间戳
const formatStamp = (count, type) => {
let countDown = {}
// ... 01天 20时 30分 20秒 29:33 常规支付限时30分钟
countDown.day = completion(Math.floor(count / 86400))
if (type) { // true : 天,时,分秒 false: 时,分,秒
countDown.hour = Math.floor(count / 3600)
countDown.hour = completion(countDown.hour >= 24 ? countDown.hour % 24 : countDown.hour)
} else {
countDown.hour = completion(Math.floor(count / 3600))
}
countDown.minutes = Math.floor(count / 60)
countDown.minutes = completion(countDown.minutes >= 60 ? countDown.minutes % 60 : countDown.minutes)
countDown.seconds = completion(count % 60)
return countDown
}
// 补全个位:1-》01
const completion = time => {
return time >= 10 ? time : `0${time}`
}
module.exports = {
completion,
formatStamp
}
ECMAScript 5 ISO-8601 日期格式支持,默认接口返回此格式
查看例子
私信加体验版
