小程序中(UniApp)动态获取当前时间

小程序中(UniApp)动态获取当前时间,第1张

准备

数据库中新建字段date,类型为datetime(精确到时分秒),date类型只精确到“天”

 

核心代码 HTML
{{dateFormat(date)}}
JS
       data() {
			return {
				date: new Date().toISOString(),
			}
		},
	    mounted() {
			let _this = this;
			setInterval(function() {
				_this.date = Date.parse(new Date());
			}, 1000);
		},
        methods: {
		dateFormat(time) {
				let date = new Date(time);
				let year = date.getFullYear();
				// 在日期格式中,月份是从0开始的,因此要加0,使用三元表达式在小于10的前面加0,以达到格式统一  如 09:11:05
				let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
				let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
				let hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
				let minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
				let seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
				// 拼接
				return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
				// return year + "-" + month + "-" + day;
			}
}
运行结果

 

 

 

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1321767.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-12
下一篇 2022-06-12

发表评论

登录后才能评论

评论列表(0条)

保存