vue 格式化時間戳


前言

有時候我們需要前端處理后端傳過來的時間戳進行格式化為日期。

Html部分

template中這樣使用,需要處理的字段名,再加上過濾器方法

<el-table-column label="日期" min-width="60">
    <template slot-scope="scope">{{scope.row.insert_time | formatDate}}</template>
</el-table-column>

第一步

首先在src目錄下建立js文件,如:date.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)
  }

第二步

在你需要使用的vue文件中,引入

import { formatDate } from '@/utils/date'

第三步

在過濾器中使用

  filters: {
    formatDate(time) {
      // 秒處理為毫秒
      time = time * 1000
      let date = new Date(time)
      console.log(new Date(time))
      return formatDate(date, 'yyyy-MM-dd hh:mm')
    },
  },


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM