美文网首页Vue
Vue 时间戳转日期格式

Vue 时间戳转日期格式

作者: 雷波_viho | 来源:发表于2017-11-17 17:48 被阅读0次

    一、方式①:
    -----先定义-----
    filters: {
    formatDate:function (date) {
    var d = new Date(date);
    var year = d.getFullYear();
    var month = d.getMonth() + 1;
    var day = d.getDate() <10 ? '0' + d.getDate() : '' + d.getDate();
    var hour = d.getHours();
    var minutes = d.getMinutes();
    var seconds = d.getSeconds();
    return year+ '-' + month + '-' + day + ' ' + hour + ':' + minutes + ':' + seconds;
    }
    ----使用----
    {{ timestamp | formatDate }}

    二、方式②
    ----定义在一个js文件中,名称为formatDate.js(名称自定义)----
    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)
    }
    ----使用----
    1.首先在.vue中引用
    import {formatDate} from '../../common/js/formatDate'
    2.然后注册
    filters: {
    formatDate (time) {
    let date = new Date(time)
    return formatDate(date, 'yyyy-MM-dd hh:mm')
    }
    }
    3.再使用
    // template
    {{ timestamp | formatDate}}

    相关文章

      网友评论

        本文标题:Vue 时间戳转日期格式

        本文链接:https://www.haomeiwen.com/subject/hvgjvxtx.html