«

vue中时间过滤器2.0

yang 发布于 阅读:377 Vue2阶段


可以过滤国际时间和本地时间,并在小时和分钟不足两位数时添加前补零

// 本地时间过滤器
Vue.filter('localTime', function(value) {
  if (!value) {
    return ''
  }
  // 将Date对象转换到本地时区
  const date = new Date(value + 'Z')
  const hours = date.getHours().toString().padStart(2, '0')
  const minutes = date.getMinutes().toString().padStart(2, '0')
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${hours}:${minutes}`
})

// 国际时间过滤器
Vue.filter('utcTime', function(value) {
  if (!value) {
    return ''
  }
  const date = new Date(value)
  const hours = date.getUTCHours().toString().padStart(2, '0')
  const minutes = date.getUTCMinutes().toString().padStart(2, '0')
  return `${date.getUTCFullYear()}-${(date.getUTCMonth() + 1).toString().padStart(2, '0')}-${date.getUTCDate().toString().padStart(2, '0')} ${hours}:${minutes}`
})

然后你就可以在 Vue 模板中使用这些过滤器

<div>
  本地时间: {{ myLocalDate | localTime }}
  <br />
  国际时间: {{ myUtcDate | utcTime }}
</div>

myLocalDate 和 myUtcDate 替换为自己需要的日期数据

vue中时间过滤器2.0

版权所有:微4e
文章标题:vue中时间过滤器2.0
除非注明,文章均为 微4e 原创,请勿用于任何商业用途,禁止转载

推荐阅读:


扫描二维码,在手机上阅读
请先 登录 再评论