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

Vue组件中如何将日期时间格式转换为指定日期格式?

Solution for Date Formatting in Vue Component

Hey there! Let's get your date formatted correctly to the 31 Mar 2018 style you need. Your current method is just manipulating the string directly, but we can use JavaScript's Date object to handle the month abbreviation and ordering properly.

Option 1: Use toLocaleDateString (Clean & Built-in)

This method leverages JavaScript's built-in locale formatting, which is concise and handles the month abbreviation automatically:

<template>
  ...
  <td>{{ getDate(item.created_at) }}</td>
  ...
</template>

<script>
export default {
  ...
  methods: {
    getDate(datetime) {
      const date = new Date(datetime);
      // Format to "Day ShortMonth Year"
      return date.toLocaleDateString('en-GB', {
        day: 'numeric',
        month: 'short',
        year: 'numeric'
      });
    }
  }
}
</script>

How it works:

  • 'en-GB' locale ensures the output follows day → month → year order
  • month: 'short' returns the 3-letter abbreviated month name (e.g., Mar for March)
  • This will reliably output 31 Mar 2018 for your input 2018-03-31 18:23:20

Option 2: Manual Month Array (Full Control)

If you want to avoid relying on locale settings (in case of inconsistent browser behavior), you can define a month abbreviation array explicitly:

<template>
  ...
  <td>{{ getDate(item.created_at) }}</td>
  ...
</template>

<script>
export default {
  ...
  methods: {
    getDate(datetime) {
      const date = new Date(datetime);
      const monthAbbr = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
      const day = date.getDate();
      const month = monthAbbr[date.getMonth()]; // getMonth() returns 0-11
      const year = date.getFullYear();
      return `${day} ${month} ${year}`;
    }
  }
}
</script>

Note about Date Parsing:

Your input string 2018-03-31 18:23:20 is compatible with new Date() in most modern browsers. If you run into parsing issues, you can replace the space with 'T' to make it a strict ISO string:

const date = new Date(datetime.replace(' ', 'T'));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:41:35