Vue中将时间数据转换成自己想要的格式

348 阅读1分钟

收到的数据时间如不是自己想要的样子,可以按照以下方法操作: 首先会用到Vue里的一个Api, 全局过滤器,用法如下图,从官网搬过来滴。

image.png

第一步:在Main.js注册全局过滤器

// 使用方法:
     Vue.filter('方法名', function() {
   //返回处理后的值
   })
 // 可复制的代码
 
 Vue.filter('forMat', (data) => {
  const t = new Date(data)    // 创建 Date 对象
  const YYYY = t.getFullYear()  //从 Date 对象以四位数字返回年份
  const MM = (t.getMonth() + 1).toString().padStart(2, 0)  //从 Date 对象返回月份 (0 ~ 11) , 故需 + 1  
  const DD = t.getDate().toString().padStart(2, 0)       //从 Date 对象返回一个月中的某一天 (1 ~ 31)
  const HH = t.getHours()    //返回 Date 对象的小时 (0 ~ 23)
  const Min = t.getMinutes()  //返回 Date 对象的分钟 (0 ~ 59)
  const SS = t.getSeconds()  //设置 Date 对象中的秒钟 (0 ~ 59)
  return `${YYYY}-${MM}-${DD} ${HH}:${Min}:${SS}`    //使用拼接字符串返回自己想要的格式
  

第二步:在组件里使用 需要使用 管道符 |

//  需要在组件里使用该过滤方法 
<el-table-column  label="入职时间">
    <template slot-scope="scoped"
  {{ scoped.row.time | forMat }}
  </template>
</el-table-column>  

如需复用,可在以上代码里添加判断条件,代码如下:

 // Main.js 里

 Vue.filter('forMat',(data, p1) => {
 const t = new Date(data)   
  const YYYY = t.getFullYear()  
  const MM = (t.getMonth() + 1).toString().padStart(2, 0)  
  const DD = t.getDate().toString().padStart(2, 0)     
  const HH = t.getHours()    
  const Min = t.getMinutes()  
  const SS = t.getSeconds()  
   // 做判断
    if (p1 === 'YYYY') {
    return `${YYYY}-${MM}-${DD}`
    }
  return `${YYYY}-${MM}-${DD} ${HH}:${Min}:${SS}`  

 // 组件里  需传参,用于做判断
 
 <el-table-column  label="入职时间">
    <template slot-scope="scoped"
  {{ scoped.row.time | forMat('YYYY') }}
  </template>
</el-table-column>  

小扩展:字符串补零的方法

image.png

 let str = '123'
 str.padStart(4, 0)   //在字符串的前面补0
 console.log(str)  //  >>>>  '0123'
 
 str.padStart(5, 0)   // >>>> '00123    以此类推
 
 str.padEnd(5, 0)  //同上, 但是是在字符串的后面补0