在社區中,發布的動態信息,經常會有一個相對余實際發布時間的相對時間。比如這里的微博:

服務端存儲的時間格式,一般為 Unix 時間戳,比如 2019/1/6 13:40:1 的Unix 時間戳為 1546753201651。前端在獲取到這個時間戳之后,會轉換為可讀格式的時間。在社交類產品中,一般會將時間戳轉換為 x 分鐘前,x 小時前或者 x 天前,因為這樣的顯示方式用戶體驗更好。
我們可以自定義一個 v-relative-time 指令來實現上述功能。
html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style type="text/css">
</style>
</head>
<body>
<div id="app" v-cloak>
現在時間:<div v-relative-time="now"></div><p></p>
2019/1/6 13:45:02:<div v-relative-time="1546753502000"></div><p></p>
2019/1/6 8:02:02:<div v-relative-time="1546732922000"></div><p></p>
2019/1/5 22:02:02:<div v-relative-time="before"></div><p></p>
2019/1/1 22:02:02:<div v-relative-time="1546351322000"></div><p></p>
2018/1/6 8:02:02:<div v-relative-time="1515196922000"></div>
</div>
<script src="https://cdn.bootcss.com/vue/2.2.2/vue.min.js"></script>
<script src="index.js"></script>
</body>
</html>
注意:div v-relative-time 指令的入參為精確到毫秒的 Unix 時間戳,如果入參單位為秒,那么可以乘以 1000 后,再傳入。
js:
/**
* 時間對象
* @type {{getCurrentUnix: Time.getCurrentUnix, getTodayUnix: Time.getTodayUnix, getThisYearUnix: Time.getThisYearUnix, format: Time.format, compensateZero: Time.compensateZero, transform: Time.transform}}
*/
var Time = {
//獲取當前 Unix 時間戳
getCurrentUnix: function () {
return new Date().getTime();
},
//獲取今日 0 點 0 分 0 秒的 Unix 時間戳
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 分 0 秒的 Unix 時間戳
getThisYearUnix: 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();
},
//格式化日期;輸出格式為 xxxx-xx-xx
format: function (val) {
var dateObj = new Date(val);
//month 代表月份的整數值從0(1月)到11(12月),所以需要轉換
var month = this.compensateZero(dateObj.getMonth() + 1);
var day = this.compensateZero(dateObj.getDate());
return dateObj.getFullYear() + '-' + month + '-' + day;
},
/**
* 如果值小于 10,那么在前面補一個零
* @param val
* @returns {*}
*/
compensateZero: function (val) {
if (typeof val == 'number') {
return val < 10 ? '0' + val : val;
} else {
return val;
}
},
/**
* 轉換為相對時間
*
* 1 分鐘之前,返回“剛剛”
* 1 分鐘到 1 小時之間,返回“xx 分鐘前”
* 1 小時到 1 天之間,返回“xx 小時前”
* 1 天到 1 個月(假設固定為 31 天)之間,返回“xx 天前”
* 大于 1 個月,返回“xx 年 xx 月 xx 日”
* @param val unix 時間戳
*/
transform: function (val) {
//計算時間間隔(單位:s)
console.log("getCurrentUnix:" + this.getCurrentUnix());
var interval = (this.getCurrentUnix() - val) / 1000;
if (Math.floor(interval / 60) <= 0) {//1 分鐘之前
return '剛剛';
} else if (interval < 3600) {//1 分鐘到 1 小時之間
return Math.floor(interval / 60) + ' 分鐘前';
} else if (interval >= 3600 && (val - this.getTodayUnix() >= 0)) {//1 小時到 1 天之間
return Math.floor(interval / 3600) + ' 小時前';
} else if (interval / (3600 * 24) <= 31) {//1 天到 1 個月(假設固定為 31 天)之間
return Math.ceil(interval / (3600 * 24)) + ' 天前';
} else {
return this.format(val);
}
}
};
時間轉換邏輯為:
我們專門設計了一個 Time 對象,用于定義與時間相關的函數:
以下是與時間相關的小知識:
Math.floor() Math.ceil()
/**
* 相對時間指令
*/
Vue.directive('relative-time', {
bind: function (el, binding) {
el.innerHTML = Time.transform(binding.value);
el._relativeTime = setInterval(function () {
el.innerHTML = Time.transform(binding.value);
}, 60000);//每分鐘,刷新一次
},
unbind: function (el) {
clearInterval(el._relativeTime);
delete el._relativeTime;
}
});
var app = new Vue({
el: '#app',
data: {
now: (new Date()).getTime(),
//2019/1/5 22:02:02
before: 1546696922000
}
});
在相對時間指令中,我們在 bind() 中,把指令中的入參轉換為相對時間,然后寫入指令所在的元素中,接著還定義了一個每分鐘更新元素內容的定時器。在 unbind() 中,執行清除定時器操作。
渲染結果:

編寫自定義指令,建議如下:
本文示例代碼
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。