vue、uniapp获取当前系统时间动态显示时分秒(类似健康码动态时间显示)

时间随着秒数,动态变化,直接上效果图

vue、uniapp获取当前系统时间动态显示时分秒(类似健康码动态时间显示)_第1张图片

时间动态实时更新




// data()数据
data() {
	return {
		timer: null,
		timeDataStr: '', // 当前系统时间
		nowTimeData: 0
	}
}


// 调用当前系统时间戳
onLoad() {
		this.getNowTimeFun()
	},
// 页面卸载关闭定时器(uniapp为例)
onUnload() {
	clearInterval(this.timer)
	this.timer = null
},

methods: {
      // 定时器
		getTime() {
			this.timer = setInterval(() => {
				this.nowTimeData = this.nowTimeData + 1000
				this.timeDataStr = this.parseTime(this.nowTimeData)
				}, 1000)
			},
		// 获取当前系统页面时间
		getNowTimeFun() {
            this.nowTimeData = new Date().getTime()
            this.getTime()
	},
	parseTime(time, cFormat) {
			if (time.length === 0) {
				return null
			}
			const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
			let date
			if (typeof time === 'object') {
				date = time
			} else {
				if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
					time = parseInt(time)
				}
				if (typeof time === 'number' && time.toString().length === 10) {
					time = time * 1000
				}
				date = new Date(time)
			}
			const formatObj = {
				y: date.getFullYear(),
				m: date.getMonth() + 1,
				d: date.getDate(),
				h: date.getHours(),
				i: date.getMinutes(),
				s: date.getSeconds(),
				a: date.getDay()
			}
			const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
				let value = formatObj[key]
				// Note: getDay() returns 0 on Sunday
				if (key === 'a') {
					return ['日', '一', '二', '三', '四', '五', '六'][value]
				}
				if (result.length > 0 && value < 10) {
					value = '0' + value
				}
				return value || 0
			})
			return time_str
		}
}

base-time组件,前面引入即可






你可能感兴趣的:(JavaScript,vue,uniapp,vue.js,uni-app,前端)