在很多论坛网站里面可以看到这样的信息:
文章发表距离当前时间的时间间隔。
我们来自定义一个指令v-time,将表达式传入的时间戳转换成相对时间。
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app">
<div v-time="timeNow"></div>
<div v-time="timeBefore"></div>
</div>
<script src="/vue.js"></script>
<script src="./time.js"></script>
<script src="./index.js"></script>
</body>
</html>
index.js
var app = new Vue({
el: '#app',
data: {
timeNow: (new Date()).getTime(),
timeBefore: 1488930695721
}
})
time.js
var Time = {
//获取当前时间戳
getUnix: function() {
var date = new Date();
return date.getTime();
},
//获取今天0点0分0秒的时间戳
getTodayUnix: function() {
var date = new Date();
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
return date.getTime();
},
//获取今年1月1日0点0秒的时间戳
getYearUnix: function() {
var date = new Date();
date.setMonth(0);
date.setDate(1);
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
return date.getTime();
},
//获取标准年月日
getLastDate: function(time) {
var date = new Date(time);
var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1;
var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
return date.getFullYear() + '-' + month + '-' + day;
},
//转换时间
getFormateTime: function(timestamp) {
var now = this.getUnix();
var today = this.getTodayUnix();
var year = this.getYearUnix();
var timer = (now - timestamp) / 1000;
var tip = '';
if (timer <= 0) {
tip = '刚刚';
} else if (Math.floor(timer / 60) <= 0) {
tip = '刚刚';
} else if (timer < 3600) {
tip = Math.floor(timer / 60) + '分钟前';
} else if (timer >= 3600 && (timestamp - today >= 0)) {
tip = Math.floor(timer / 3600) + '小时前';
} else if (timer / 86400 <= 31) {
tip = Math.ceil(timer / 86400) + '天前';
} else {
tip = this.getLastDate(timestamp);
}
return tip;
}
}
Vue.directive('time', {
bind: function(el, binding) {
el.innerHTML = Time.getFormateTime(binding.value);
el.__timeout__ = setInterval(() => {
el.innerHTML = Time.getFormateTime(binding.value);
}, 60000);
},
unbind: function() {
clearInterval(el.__timeout__);
delete el.__timeout__;
}
})