admin管理员组

文章数量:1538140

刚开始写的时候是用这种方式转换的

// 时间格式转换
Vue.filter('dateFormat', function (origin) {
  const newDate = new Date(origin);
  const n = newDate.getFullYear();
  const y = (newDate.getMonth() + 1 + '').padStart('2', '0');
  const r = (newDate.getDay() + '').padStart('2', '0');
  const s = (newDate.getHours() + '').padStart('2', '0');
  const f = (newDate.getMinutes() + '').padStart('2', '0');
  const m = (newDate.getSeconds() + '').padStart('2', '0');
  return `${n}/${y}/${r} ${s}:${f}:${m}`
})

但是这边就出现这样的情况,如下图

然后我们可以通过moment转换
首先npm或cnpm install moment --save 来下载依赖,然后在main.js中引入moment,然后通过filter过滤

具体的moment更多转换见官网http://momentjs/

import moment from 'moment';

// 定义全局时间戳过滤器
 Vue.filter('formatDate', function(value) {
   return moment(value).format('YYYY-MM-DD HH:mm:ss')
 })

但是吧,项目中又出现问题了,如图

页面中是这样的Invalid date 无效的日,很气人吧,这个原因是后端返回的时间戳是一个字符串,这个时候我们可以将字符串转换成数字

// 定义全局时间戳过滤器
 Vue.filter('formatDate', function(value) {
   return moment(Number(value)).format('YYYY-MM-DD HH:mm:ss')
 })

这样就解决问题啦

本文标签: 格式转换时间项目vue