vue中将时间戳转换为YYYY-MM-dd hh:mm格式时间的组件

首先我们可以使用vue中的过滤方法将数据变成另一个格式

// html
<span class="rate-time">{{rating.rateTime | formateDate}}</span>
 
//script
filters: {
  formateDate (time) {
    let date = new Date(time)
    return formateDate(date, 'YYYY-MM-dd hh:mm')
}

要使用通用的formateDate函数,我们可以在common/js下新建一个date.js文件,并导出一个函数

export function formateDate (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
}
// 左边补0函数
function padLeftZero (str) {
  return ('00' + str).substr(str.length)
}

在要使用的组件中导入这个方法即可:

import { formateDate } from 'common/js/date'

原文地址: https://blog.csdn.net/Vansal/article/details/89424862

猜你喜欢

转载自www.cnblogs.com/Antwan-Dmy/p/11990021.html