Skip to content

日期格式化 dateFormat

赞助

格式化日期为指定格式的工具函数

Show Source Code
ts
/**
 * 格式化日期时间字符串
 *
 * @param {number | string | Date} [value = Date.now()] 待格式化的日期时间值,支持数字、字符串和 Date 类型,默认为当前时间戳
 * @param {string} [format = 'YYYY-MM-DD HH:mm:ss'] 格式化字符串,默认为'YYYY-MM-DD HH:mm:ss',支持格式化参数:YY:年,M:月,D:日,H:时,m:分钟,s:秒,SSS:毫秒
 * @returns {string} 返回格式化后的日期时间字符串
 */
export function dateFormat(value: number | string | Date = Date.now(), format: string = 'YYYY-MM-DD HH:mm:ss'): string {
  try {
    let date: Date
    if (typeof value === 'number' || typeof value === 'string') {
      date = new Date(value)
      if (isNaN(date.getTime())) {
        throw new Error('Invalid date')
      }
    } else {
      date = value
    }
    const padZero = (value: number, len: number = 2): string => {
      // 左侧补零函数
      return String(value).padStart(len, '0')
    }
    const replacement = (match: string) => {
      switch (match) {
        case 'YYYY':
          return padZero(date.getFullYear())
        case 'YY':
          return padZero(date.getFullYear()).slice(2, 4)
        case 'MM':
          return padZero(date.getMonth() + 1)
        case 'M':
          return String(date.getMonth() + 1)
        case 'DD':
          return padZero(date.getDate())
        case 'D':
          return String(date.getDate())
        case 'HH':
          return padZero(date.getHours())
        case 'H':
          return String(date.getHours())
        case 'mm':
          return padZero(date.getMinutes())
        case 'm':
          return String(date.getMinutes())
        case 'ss':
          return padZero(date.getSeconds())
        case 's':
          return String(date.getSeconds())
        case 'SSS':
          return padZero(date.getMilliseconds(), 3)
        default:
          return match
      }
    }
    return format.replace(/(YYYY|YY|M{1,2}|D{1,2}|H{1,2}|m{1,2}|s{1,2}|SSS)/g, replacement)
  } catch (error) {
    console.error('Error formatting date:', error)
    return ''
  }
}

基本使用

格式化时间戳


2026-09-15 15:19:09
vue
<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { dateFormat } from 'vue-amazing-ui'
const date = ref(dateFormat(new Date()))
let rafId = 0
const updateDate = () => {
  date.value = dateFormat(new Date())
  rafId = requestAnimationFrame(updateDate)
}
// SSR(Node)环境无 requestAnimationFrame:挂载后启动,卸载时取消
onMounted(() => {
  rafId = requestAnimationFrame(updateDate)
})
onBeforeUnmount(() => {
  cancelAnimationFrame(rafId)
})
</script>

格式化字符串

10/10/2025
vue
<script setup lang="ts">
import { dateFormat } from 'vue-amazing-ui'
dateFormat('2025-10-10', 'MM/DD/YYYY') // 10/10/2025
</script>

展示毫秒值

2026-09-15 15:19:09:045
vue
<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { dateFormat } from 'vue-amazing-ui'
const realTime = ref(dateFormat(Date.now(), 'YYYY-MM-DD HH:mm:ss:SSS'))
let rafId = 0
const updateTime = () => {
  realTime.value = dateFormat(Date.now(), 'YYYY-MM-DD HH:mm:ss:SSS')
  rafId = requestAnimationFrame(updateTime)
}
// SSR(Node)环境无 requestAnimationFrame:挂载后启动,卸载时取消
onMounted(() => {
  rafId = requestAnimationFrame(updateTime)
})
onBeforeUnmount(() => {
  cancelAnimationFrame(rafId)
})
</script>

Params

参数说明类型默认值
value待格式化的日期时间值,支持数字、字符串和 Date 类型,默认为当前时间戳number | string | DateDate.now()
format格式化字符串string'YYYY-MM-DD HH:mm:ss'

Return

类型说明
string格式化后的日期时间字符串

format 支持的格式化占位符列表

标识示例描述
YY23年,两位数
YYYY2023年,四位数
M1-12月,从 1 开始
MM01-12月,两位数
D1-31
DD01-31日,两位数
H0-23小时
HH00-23小时,两位数
m0-59分钟
mm00-59分钟,两位数
s0-59
ss00-59秒,两位数
SSS000-999毫秒,三位数

注意事项

  • 传入无法解析的日期值时返回空字符串 '',并在控制台输出错误信息

Released under the MIT License.