vue时间戳组件

196 阅读1分钟
<template>
	<view class="">
		<view v-for="item in contList">{{fmtTime(item.timer)}}</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				contList:[
					{timer:"2020-11-03 8:10:59"},
					{timer:"2020-11-03 3:10:59"},
					{timer:"2020-11-01 8:10:59"},
				]
			}

		},
		methods: {
			addZero(num) {
				num = num.toString();
				return num[1] ? num : "0" + num;
			},
			fmtTime(str) {
				let now = new Date();
				let thatTime = new Date(str);
				//now - thatTime  结果为相差的毫秒数,
				let totalSec = Math.floor((now - thatTime) / 1000); //获得秒钟
				if (totalSec < 60) return "刚刚";
				//1小时以内显示多少分钟前
				else if (totalSec < 60 * 60) return Math.floor(totalSec / 60) + "分钟前";
				//1天以内显示多少小时前
				else if (totalSec < 60 * 60 * 24) return Math.floor(totalSec / 60 / 60) + "小时前"
				//大于一天则显示具体的时间
				else return [thatTime.getFullYear(), this.addZero(thatTime.getMonth() + 1),
						this.addZero(thatTime.getDate())
					].join("-") + " " + [this.addZero(thatTime.getHours()), this.addZero(thatTime.getMinutes()), this.addZero(thatTime.getSeconds())]
					.join(":");
			}
		}
	}
</script>

<style>
</style>