其他分享
首页 > 其他分享> > 使用filters实现时间过滤

使用filters实现时间过滤

作者:互联网

模拟微信朋友圈的时间显示格式
在这里插入图片描述
代码实现:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>时间过滤</title>
	</head>
	<body>
		<div id="app">
			<h1>{{datetime1|dateFormat}}</h1>
			<h1>{{datetime2|dateFormat}}</h1>
			<h1>{{datetime3|dateFormat}}</h1>
			<h1>{{datetime4|dateFormat}}</h1>
			<h1>{{datetime5|dateFormat}}</h1>
			<h1>{{datetime6|dateFormat}}</h1>
		</div>
		<script src="js/vue.js"></script>
		<script>
			const vm = new Vue({
				el:'#app',
				data:{
					//模拟发朋友圈的时间
					datetime1:new Date('2021/10/8 17:54:52'),
					datetime2:new Date('2021/10/8 13:42:10'),
					datetime3:new Date('2021/10/8 12:04:52'),
					datetime4:new Date('2021/10/7 11:04:52'),
					datetime5:new Date('2021/10/6 10:04:52'),
					datetime6:new Date('2021/9/30 10:55:52')
				},
				filters:{
					dateFormat(date){
						//获取当前时间的毫秒值
						const now  = new Date().getTime();
						//获取过滤时间的毫秒值
						const datetime = date.getTime();
						//计算出两个时间之间相差的秒值
						const interval = (now-datetime)/1000;
						//判断
						if(interval<60){
							return '刚刚'
						}else if(interval<(60*60)){
							return `${parseInt(interval/60)}分钟前`
						}else if(interval<(60*60*24)){
							return `${parseInt(interval/60/60)}小时前`
						}else if(interval<(60*60*24*2)){
							return '昨天'
						}else if(interval<(60*60*24*8)){
							return `${parseInt(interval/60/60/24)}天前`
						}else{
							let year = date.getFullYear();
							let month = date.getMonth()+1;
							month = month<10?`0${month}`:month;
							let day = date.getDate();
							day = day<10?`0${day}`:day;
							let h = date.getHours();
							h = h<10?`0${h}`:h;
							let m = date.getMinutes();
							m = m<10?`0${m}`:m;
							let s = date.getSeconds();
							s = s<10?`0${s}`:s;
							return `${year}-${month}-${day} ${h}:${m}:${s}`
						}
						
					}
				}
			});
		</script>
	</body>
</html>

标签:10,dateFormat,实现,interval,Date,过滤,filters,date,new
来源: https://blog.csdn.net/weixin_41092938/article/details/120656853