uniapp倒计时功能

文章描述:

uniapp倒计时功能,获取当前日期时间或者指定日期时间,进行计算倒计时

获取时间与时间格式转换

var date = new Date('2023-02-24T20:13:14.669+08:00')
console.log("时间格式:",date)
				
let y = new Date(date).getFullYear()
let m = new Date(date).getMonth()+1;
let d = new Date(date).getDate()
let H = new Date(date).getHours()
let i = new Date(date).getMinutes()
let s = new Date(date).getSeconds()

if(m<10){
    m = '0' + m
}
if(d<10){
   d = '0' + d
}
let datetime = `${y}-${m}-${d} ${H}:${i}:${s}`;
console.log(datetime);

时间格式: Fri Feb 24 2023 20:13:14 GMT+0800 (中国标准时间)

2023-02-24 20:13:14

完整案例

template

<template>
	<view class="content">
		<view class="time">
				<text>还剩</text>
				<view class="shijian">{{countdownh}}</view>
				<text>时</text>
				<view class="shijian">{{countdownm}}</view>
				<text>分</text>
				<view class="shijian">{{countdowns}}</view>
				<text>秒</text>
		</view>
	</view>
</template>

script

var _self;
export default{
	data(){
		return{
			countdownh:'',
			countdownm:'',
			countdowns:'',
			timer: null, // 重复执行
			endTime:'',	 // 结束日期
		}
	},
	onLoad() {
		_self = this
	},
	onShow() {
		// 结束时间
		var date = new Date('2023-02-24T20:13:14.669+08:00') //	2023-02-23T11:44:15.669+08:00
		console.log("时间格式:",date)
				
		let y = new Date(date).getFullYear()
		let m = new Date(date).getMonth()+1;
		let d = new Date(date).getDate()
		let H = new Date(date).getHours()
		let i = new Date(date).getMinutes()
		let s = new Date(date).getSeconds()
		
		if(m<10){
		    m = '0' + m
		}
		if(d<10){
		    d = '0' + d
		}
		let datetime = `${y}-${m}-${d} ${H}:${i}:${s}`;
		
		// 结束时间戳
		var dateNow = new Date()
		var timeStampNow = Date.parse(dateNow)
		_self.endTime = timeStampNow + 1000*60*60*2
		
		this.timer = setInterval(()=>{
			this.showtime()
		})
	},
	methods:{
		showtime () {
				
				var timeStamp = _self.endTime
				
				// 当前时间戳
				var dateNow = new Date()
				var timeStampNow = Date.parse(dateNow)
				
				
				var lefttime = timeStamp - timeStampNow,
				leftd = Math.floor(lefttime/(1000*60*60*24)),  //计算天数
				lefth = Math.floor((lefttime/(1000*60*60)%24)+leftd*24) < 10 ? "0" + Math.floor((lefttime/(1000*60*60)%24)+leftd*24) : Math.floor((lefttime/(1000*60*60)%24)+leftd*24),  //计算小时数
				leftm = Math.floor(lefttime/(1000*60)%60) < 10 ? "0" + Math.floor(lefttime/(1000*60)%60) : Math.floor(lefttime/(1000*60)%60),  //计算分钟数
				lefts = Math.floor(lefttime/1000%60) < 10 ? "0" + Math.floor(lefttime/1000%60) : Math.floor(lefttime/1000%60);  //计算秒数
				this.countdownh = lefth  //返回倒计时的字符串
				this.countdownm = leftm	 //返回倒计时的字符串
				this.countdowns = lefts  //返回倒计时的字符串
				
				console.log(lefttime)
				// 倒计时结束时,显示00:00:00
				if(lefttime == 0) {
					this.countdownh = this.countdownm= this.countdowns = "00"
					clearInterval(this.timer);
				}
		}
		//...
	}
}

style

.time{
	display: flex;
	justify-content: flex-start;
	view{
		color: red;
	}
}

 

发布时间:2023/02/24

发表评论