前端開發
day.js 搭配 Vue 3 的日期格式化
整理 Vue 3 日期格式化的常見做法,使用 day.js 取代舊專案常見的 moment.js,並以 method 或 computed 取代 Vue 2 filter,也補充原生 Intl.DateTimeFormat 的使用方式。
W
- Vue 2 時期常用 moment.js 搭配全域 filter 做日期格式化。
- Moment.js 目前已經進入維護模式,而 Vue 3 也移除了 filter 語法。
- 現在可以改用 day.js,或只是單純顯示日期時直接使用瀏覽器內建的
Intl.DateTimeFormat。
安裝 day.js
npm install dayjs
基本格式化:
import dayjs from 'dayjs'
dayjs('2026-08-19').format('YYYY-MM-DD')
// '2026-08-19'
dayjs('2026-08-19').format('YYYY.MM.DD')
// '2026.08.19'
day.js 的 API 和 Moment.js 相近,但核心比較精簡,需要 UTC、timezone 等功能時再另外載入 plugin。
Vue 3 取代 filter
Vue 2 以前可以寫:
{{ item.paidDate | dateFormat }}
Vue 3 已經移除 filter,現在直接呼叫一般函式即可:
<script setup>
import dayjs from 'dayjs'
function dateFormat(value, format = 'YYYY-MM-DD') {
return dayjs(value).format(format)
}
</script>
<template>
<span>
{{ dateFormat(item.paidDate, 'YYYY.MM.DD') }}
</span>
</template>
需要傳入不同日期或格式時,用一般函式會比較方便。
使用 computed
如果顯示內容是由元件內的 reactive state 或 props 衍生而來,也可以使用 computed:
<script setup>
import { computed } from 'vue'
import dayjs from 'dayjs'
const props = defineProps({
paidDate: String
})
const formattedDate = computed(() => {
return dayjs(props.paidDate).format('YYYY.MM.DD')
})
</script>
<template>
<span>{{ formattedDate }}</span>
</template>
可以簡單區分:
需要傳參數或處理多筆資料
→ 一般函式
由 props / state 衍生固定顯示值
→ computed
UTC 與時區
需要處理 UTC 時,可以使用 day.js plugin:
import dayjs from 'dayjs'
import utc from 'dayjs/plugin/utc'
import timezone from 'dayjs/plugin/timezone'
dayjs.extend(utc)
dayjs.extend(timezone)
例如後端回傳的時間確定是 UTC:
function formatFromUTC(value, format = 'YYYY-MM-DD HH:mm') {
return dayjs.utc(value).local().format(format)
}
- 這會先按照 UTC 解讀,再轉成使用者目前的本地時區。
- 如果來源本來就是 local time,就不要額外使用
utc()。
不裝套件:Intl.DateTimeFormat
如果只是顯示日期,不需要日期加減、比較或複雜操作,可以直接使用瀏覽器內建的 Intl.DateTimeFormat:
const formatter = new Intl.DateTimeFormat('zh-TW', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
})
function formatDate(value) {
return formatter.format(new Date(value))
}
使用:
formatDate('2026-08-19')
// 2026/08/19
Intl.DateTimeFormat 會根據指定的 locale 處理在地化日期格式,不需要額外安裝套件。
怎麼選
| 情況 | 建議 |
|---|---|
| 單純顯示在地化日期 | Intl.DateTimeFormat |
自訂 YYYY-MM-DD 等格式 | day.js |
| 日期加減、比較 | day.js |
| UTC / timezone 處理 | day.js + plugin |
| Vue 2 filter 遷移 | method 或 computed |
小結
Vue 3 已經沒有:
{{ value | dateFormat }}
可以改成:
{{ dateFormat(value) }}
或把 reactive state 的格式化結果寫成:
const formattedDate = computed(() => {
return dayjs(value.value).format('YYYY-MM-DD')
})
如果只是做在地化日期顯示,則可以先考慮:
new Intl.DateTimeFormat('zh-TW')
不一定每個日期格式化需求都需要另外安裝 day.js。