萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 日期格式化通用函數:支援 yyyy-MM-dd HH:mm:ss 等任意格式

前言

JS 原生 Date 格式化功能極弱,常需自寫格式化函數。本文提供一個健壯、支援任意格式字串(如 yyyy-MM-dd HH:mm:ss.S)的 dateFormat 函數,並說明原理與現代替代方案。

通用格式化函數 (ES6+ 版)

/**
 * 日期格式化
 * @param {Date|number|string} date 日期物件/時間戳/可解析字串
 * @param {string} format 格式字串,支援:y/M/d/h/m/s/q/S
 * @returns {string} 格式化後字串
 */
function dateFormat(date, format = 'yyyy-MM-dd HH:mm:ss') {
    if (!(date instanceof Date)) date = new Date(date);
    if (isNaN(date)) return 'Invalid Date';

    const o = {
        'M+': date.getMonth() + 1,     // 月份 1-12
        'd+': date.getDate(),          // 日期 1-31
        'h+': date.getHours(),         // 小時 0-23
        'm+': date.getMinutes(),       // 分鐘 0-59
        's+': date.getSeconds(),       // 秒 0-59
        'q+': Math.floor((date.getMonth() + 3) / 3), // 季度 1-4
        'S' : date.getMilliseconds()   // 毫秒 0-999
    };

    // 年份處理:yyyy / yy
    if (/(y+)/.test(format)) {
        const yearStr = date.getFullYear().toString();
        format = format.replace(RegExp.$1, yearStr.slice(4 - RegExp.$1.length));
    }

    // 其他欄位:支援單字元 (M) 或雙字元 (MM) 自動補零
    for (const k in o) {
        if (new RegExp(`(${k})`).test(format)) {
            const val = o[k].toString();
            const len = RegExp.$1.length;
            const replacement = len === 1 ? val : val.padStart(len, '0');
            format = format.replace(RegExp.$1, replacement);
        }
    }
    return format;
}

使用範例

const now = new Date();
console.log(dateFormat(now));                    // 2024-12-19 14:30:05
console.log(dateFormat(now, 'yyyy/MM/dd'));      // 2024/12/19
console.log(dateFormat(now, 'yy-M-d h:m:s'));    // 24-12-19 14:30:5
console.log(dateFormat(now, 'yyyy年MM月dd日'));   // 2024年12月19日
console.log(dateFormat(now, 'HH:mm:ss.SSS'));    // 14:30:05.123
console.log(dateFormat('2023-01-01', 'q'));      // 1 (第一季)

格式字元對照表

字元含義範例
y / yy / yyyy年份 (兩位/四位)24 / 2024
M / MM月份 (不補零/補零)1 / 01
d / dd日期5 / 05
h / hh小時 (24制)9 / 09
H / HH小時 (12制,需自行擴充)--
m / mm分鐘3 / 03
s / ss秒7 / 07
q季度1-4
S / SS / SSS毫秒 (1/2/3 位)5 / 05 / 005

現代替代方案

1. Intl.DateTimeFormat (原生、無依賴、支援多語系)

const fmt = new Intl.DateTimeFormat('zh-TW', {
    year: 'numeric', month: '2-digit', day: '2-digit',
    hour: '2-digit', minute: '2-digit', second: '2-digit',
    hour12: false
});
console.log(fmt.format(new Date())); // 2024/12/19 14:30:05

2. Temporal API (Stage 3,未來標準)

// 目前需 Polyfill
import { Temporal } from '@js-temporal/polyfill';
const dt = Temporal.Now.plainDateTimeISO();
console.log(dt.toString({ smallestUnit: 'millisecond' })); // 2024-12-19T14:30:05.123

3. 輕量庫推薦

  • date-fns:format(date, 'yyyy-MM-dd HH:mm:ss'),模組化、Tree-shaking 友善。
  • Day.js:dayjs().format('YYYY-MM-DD HH:mm:ss'),API 兼容 Moment、體積 2KB。
  • Moment.js:維護模式,新專案不建議引入。

避坑指南

  • 月份 getMonth() 回傳 0-11,**記得 +1**。
  • 星期 getDay() 回傳 0(日)-6(六),格式化常需自行對照表。
  • 時區:new Date() 使用本地時區,傳輸建議用 ISO 字串 (toISOString()) 或 Timestamp。
  • 避免在熱點路徑頻繁建立 Date 與正則,可緩存編譯後的 RegExp 或使用庫函數。
copyright © 萬盛學電腦網 all rights reserved