You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Vue 2中使用Moment.js格式化后端时间为日期格式

解决Vue2中使用Moment格式化日期为YYYY-MM-DD格式的问题

方法一:修改已有的computed属性

你已经在computed中定义了基于moment的格式化方法,只需替换格式字符串即可:

  1. 找到computed中的对应方法,原代码大概是这样:
computed: {
  formattedBlogDate() {
    return moment(this.blog.date).format('MMMM Do YYYY, h:mm:ss a')
  }
}
  1. 将format()的参数改为'YYYY-MM-DD',如果要避免本地时区偏移导致日期偏差(比如后端返回的是UTC时间),可以加上.utc():
computed: {
  formattedBlogDate() {
    return moment(this.blog.date).utc().format('YYYY-MM-DD')
  }
}
  1. 在模板里把{{ blog.date }}替换为{{ formattedBlogDate }},就能渲染出2023-03-18格式的日期。

方法二:使用Vue过滤器(适合批量处理多个日期)

如果页面里有多处需要格式化的日期,定义过滤器更高效:

  1. 在组件的filters选项中添加过滤器:
filters: {
  formatDate(date) {
    return moment(date).utc().format('YYYY-MM-DD')
  }
}
  1. 在模板中直接调用过滤器:
<!-- 单个日期渲染 -->
{{ blog.date | formatDate }}

<!-- 列表循环中的日期渲染 -->
<div v-for="blog in blogList" :key="blog.id">
  {{ blog.date | formatDate }}
</div>

注意事项

  • 确保项目已正确引入moment库,组件内可正常调用moment方法。
  • 如果后端返回的UTC时间转本地时间后会跨零点,一定要加.utc()来保留原始日期。

内容的提问来源于stack exchange,提问作者xander

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 21:05:06