• 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')
        },
      },
    
  • 相关阅读:
    Sql Server增删改查字段的语法
    Django-2
    Django-1
    Django自学历程
    前端之bootstrap框架
    前端之JQuery
    前端之DOM
    前端之BOM
    前端之JavaScript
    前端之css
  • 原文地址:https://www.cnblogs.com/niuben/p/14710393.html
Copyright © 2020-2023  润新知