vue.js將時間戳轉(zhuǎn)化為日期格式的實現(xiàn)代碼
更新時間:2018年06月05日 11:37:43 作者:舊夢空城人心涼
這篇文章主要介紹了vue.js將時間戳轉(zhuǎn)化為日期格式的實現(xiàn)代碼,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下
看看下面的代碼吧,具體代碼如下所示:
<!-- value 格式為13位unix時間戳 --> <!-- 10位unix時間戳可通過value*1000轉(zhuǎn)換為13位格式 -->
export function formatDate (date, fmt) {
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
}
let o = {
'M+': date.getMonth() + 1,
'd+': date.getDate(),
'h+': date.getHours(),
'm+': date.getMinutes(),
's+': date.getSeconds()
};
for (let k in o) {
if (new RegExp(`(${k})`).test(fmt)) {
let str = o[k] + '';
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str));
}
}
return fmt;
};
function padLeftZero (str) {
return ('00' + str).substr(str.length);
};
把上面代碼保存為date.js放到你的公共js文件夾中。
在你的需要格式化時間戳的組件里像下面這樣使用:
<template>
<!-- 過濾器 time 可以使后臺得到的數(shù)據(jù),循環(huán)出來的也行 -->
<div>{{time | formatDate}}</div>
<!-- 輸出結(jié)果 -->
<!-- <div>2016-07-23 21:52</div> -->
</template>
<script>
import {formatDate} from './common/date.js';
export default {
filters: {
formatDate(time) {
var date = new Date(time);
return formatDate(date, 'yyyy-MM-dd hh:mm');
}
}
}
</script>
總結(jié)
以上所述是小編給大家介紹的vue.js將時間戳轉(zhuǎn)化為日期格式的實現(xiàn)代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!

