vue - 时间过滤器(全局注册)

utils/filter.js

/*
 * @Author: lingxie
 * @Date: 2020-06-04 13:43:42
 * @Descripttion: 
 */ 
/**
 * @method: formatTime
 * @des: 时间格式化
 * @param {time} 时间戳或者时间对象
 * @param {type} 时间类型
 * @return: 
 */
const formatTime = (time, type) => {
    var date;
    //判断传入的是时间戳还是时间对象
    if (time instanceof Date) { 
        date = time;
    } else {
        date = new Date(time)
    }
    var y = date.getFullYear();
    var m = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) * 1 : date.getMonth() + 1;
    var d = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    var h = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
    var minute = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
    var second = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
    switch (type) {
        case 'yy-mm-dd hh:mm:ss':
            return y + "-" + m + "-" + d + " " + h + ":" + minute + ":" + second;
        case 'yy-mm-dd type':
            return y + "-" + m + "-" + d + " " + (h === 13 ? '下午' : '上午');
        case 'yy-mm-dd hh:mm':
            return y + "-" + m + "-" + d + " " + h + ":" + minute;
        case 'yy/mm/dd hh:mm:ss':
            return y + "/" + m + "/" + d + " " + h + ":" + minute + ":" + second;
        case 'yy-mm-dd':
            return y + "-" + m + "-" + d;
        case 'yy.mm.dd':
            return y + "." + m + "." + d;
        case 'yy.mm.dd hh:mm:ss':
            return y + "." + m + "." + d + " " + h + ":" + minute + ":" + second;
        case 'mm-dd hh:mm':
            return m + "-" + d + " " + h + ":" + minute;
    }

}

export {
    formatTime,
}

main.js  【全局注册过滤器】

/*
 * @Author: lingxie
 * @Date: 2020-04-23 13:35:57
 * @Descripttion: 
 */ 
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false

//引入过滤器文件
import * as filters from './utils/filter'

// 添加全局过滤器
Object.keys(filters).forEach(key => {
  Vue.filter(key, filters[key])
})


new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

页面使用:

 <h3>时间格式化</h3>
 <div>{{ 1588571766000 | formatTime('yy-mm-dd') }}</div>
 <div>{{'Mon May 04 2020 13:30:29 GMT+0800 (中国标准时间)' | formatTime('yy-mm-dd hh:mm:ss')}}</div>

 

效果:

 

posted @ 2020-06-04 14:11  邪儿莫  阅读(530)  评论(1编辑  收藏  举报