Vue组件中如何将日期时间格式转换为指定日期格式?
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 ordermonth: 'short'returns the 3-letter abbreviated month name (e.g.,Marfor March)- This will reliably output
31 Mar 2018for your input2018-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

