vue 将时间戳转换成日期格式 ,一

(1)创建一个处理时间格式的js,内容如下:

../../utils/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)
}

(2)在vue文件中需要格式化时间戳的地方,使用filters过滤器,做如下处理:

<template>
  <div class="date">{{item.pass_time | formatDate}}</div>
</template>
 
<script type="text/ecmascript-6">
// 引入formatDate.js 文件 import {formatDate} from '../../utils/formatDate.js'
export default { filters: {
 //方法一: yyyy-MM-dd hh:mm formatDate(time) { time = time * 1000 let date = new Date(time) console.log(new Date(time)) return formatDate(date, 'yyyy-MM-dd hh:mm') }
     //方法二: yyyy-MM-dd
      formatDate(time) {
        // time = time * 1000
        let date = new Date(time)
        console.log(new Date(time))
        return formatDate(date, 'yyyy-MM-dd')
      }
} }
</script>

  补充:time应为格式为13位unix时间戳,如果拿到的时间戳是10位的unix时间戳,因此需要乘以1000。

转载地址: https://blog.csdn.net/qq_32678401/article/details/81983364