vue中时间戳转换为日期格式的方法封装

/*
date:需要转换的时间戳
fmt:需要转换的日期格式
*/
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)
}

在需要转换的地方使用过滤器进行过滤,如果很多地方都需要转换,那么可以在main.js中写成全局过滤器

filters: {
    
    
    formatDate(time) {
    
    
      time = time * 1000;//如果时间戳是10位,就需要*1000,如果是13位,就不需要
      //将时间戳转换为对应时间的时间对象
      let date = new Date(time);
      return formatDate(date, "yyyy-MM-dd hh:mm");
    },
  },

猜你喜欢

转载自blog.csdn.net/fangqi20170515/article/details/126698147