vue 日期时间过滤器

来自:https://blog.csdn.net/m0_37068028/article/details/72898154 侵删

来自:https://segmentfault.com/a/1190000010378259 侵删

第一种:

// template
{{date | formatDate}}

//script
import {formatDate} from '../../common/js/date'
filters: {
  formatDate (time) {
     let date = new Date(time) return formatDate(date, 'yyyy-MM-dd hh:mm')
  }
}

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


第二种:

npm install moment --save 
main.js 中 
import moment from 'moment/moment'

添加过滤器:
Vue.filter('moment', function (value, formatString) {
    formatString = formatString || 'YYYY-MM-DD HH:mm:ss';
    // return moment(value).format(formatString); // value可以是普通日期 20170723
    return moment.unix(value).format(formatString); // 这是时间戳转时间
});

/* eslint-disable no-new */
new Vue({
  el: '#app',
  template: '<App/>',
  components: { App }
})
页面中使用
<template>
  <div id="app">
      <div>
        {{ datetime | moment }}
      </div>
  </div>
</template>

<script>
export default {
  name: 'app',
  data () {
    return {
      datetime: '1500799859'
    }
  }
}
</script>

结果:

2017-07-23 16:50:59



原文地址:https://www.cnblogs.com/Byme/p/10108993.html