首页 > 其他 > 详细

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

时间:2019-12-05 16:04:36      阅读:122      评论:0      收藏:0      [点我收藏+]

 

(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

 

 

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

原文:https://www.cnblogs.com/Antwan-Dmy/p/11989134.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!