萬盛學電腦網

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

JavaScript 日期時間格式化完全指南:內建方法、自定義格式化函數與現代 API

Date 內建格式化方法速查

方法輸出示例說明
toString()"Mon Nov 04 2013 22:03:05 GMT+0800 (中國標準時間)"完整日期時間字符串
toDateString()"Mon Nov 04 2013"僅日期部分
toTimeString()"22:03:05 GMT+0800 (中國標準時間)"僅時間部分
toLocaleString()"2013年11月4日 下午10:03:05"本地化格式 (依運行環境)
toLocaleDateString()"2013年11月4日"本地化日期
toLocaleTimeString()"下午10:03:05"本地化時間
toISOString()"2013-11-04T14:03:05.420Z"ISO 8601 UTC 標準格式
toJSON()"2013-11-04T14:03:05.420Z"同 toISOString(),JSON 序列化用
toGMTString()"Mon, 04 Nov 2013 14:03:05 GMT"已棄用,用 toUTCString()
toUTCString()"Mon, 04 Nov 2013 14:03:05 GMT"UTC 時間字符串

自定義格式化函數 (擴展 Date.prototype)


Date.prototype.format = function(fmt) {
    var o = {
        'M+': this.getMonth() + 1,     // 月份 1-12
        'd+': this.getDate(),          // 日期 1-31
        'h+': this.getHours(),         // 小時 0-23
        'H+': this.getHours(),         // 別名
        'm+': this.getMinutes(),       // 分鐘 0-59
        's+': this.getSeconds(),       // 秒 0-59
        'q+': Math.floor((this.getMonth() + 3) / 3), // 季度 1-4
        'S+': this.getMilliseconds()   // 毫秒 0-999
    };
    
    // 年份特殊處理:yyyy / yy
    if (/(y+)/i.test(fmt)) {
        var yearStr = this.getFullYear() + '';
        fmt = fmt.replace(RegExp.$1, yearStr.substr(4 - RegExp.$1.length));
    }
    
    // 其他字段:長度 1 不補零,長度 2 補零
    for (var k in o) {
        if (new RegExp('(' + k + ')').test(fmt)) {
            var val = o[k] + '';
            fmt = fmt.replace(RegExp.$1, 
                RegExp.$1.length === 1 ? val : ('00' + val).substr(val.length));
        }
    }
    return fmt;
};

// 使用示例
var now = new Date();
console.log(now.format('yyyy-MM-dd'));           // 2024-01-15
console.log(now.format('yyyy-MM-dd hh:mm:ss'));  // 2024-01-15 14:30:05
console.log(now.format('yyyy/MM/dd'));           // 2024/01/15
console.log(now.format('yy年M月d日'));           // 24年1月15日
console.log(now.format('hh:mm:ss.S'));           // 14:30:05.123

ES6 模板字符串輔助函數 (不污染原型)


const formatDate = (date, fmt = 'yyyy-MM-dd hh:mm:ss') => {
    const o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds(),
        'q+': Math.floor((date.getMonth() + 3) / 3),
        'S+': date.getMilliseconds()
    };
    
    if (/(y+)/i.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    
    for (const k in o) {
        if (new RegExp('(' + k + ')').test(fmt)) {
            const val = o[k] + '';
            fmt = fmt.replace(RegExp.$1, 
                RegExp.$1.length === 1 ? val : ('00' + val).substr(val.length));
        }
    }
    return fmt;
};

現代標準:Intl.DateTimeFormat (零依賴、國際化、高效能)


// 基礎用法
const dtf = new Intl.DateTimeFormat('zh-CN', {
    year: 'numeric', month: '2-digit', day: '2-digit',
    hour: '2-digit', minute: '2-digit', second: '2-digit',
    hour12: false
});
console.log(dtf.format(new Date())); // "2024/01/15 14:30:05"

// 組合自定義格式
function formatIntl(date, locale = 'zh-CN') {
    const opts = {year: 'numeric', month: '2-digit', day: '2-digit',
                  hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false};
    const parts = new Intl.DateTimeFormat(locale, opts).formatToParts(date);
    const map = Object.fromEntries(parts.map(p => [p.type, p.value]));
    return `${map.year}-${map.month}-${map.day} ${map.hour}:${map.minute}:${map.second}`;
}

// 相對時間格式化 (如 "2小時前")
const rtf = new Intl.RelativeTimeFormat('zh-CN', {numeric: 'auto'});
console.log(rtf.format(-2, 'hour')); // "2小時前"
console.log(rtf.format(-3, 'day'));  // "3天前"

第三方庫推薦 (複雜業務)

  • date-fns:模塊化、Tree-shaking 友好、TypeScript 優先、format(date, 'yyyy-MM-dd')。
  • dayjs:2KB 輕量、API 與 Moment.js 兼容、dayjs().format('YYYY-MM-DD')。
  • Moment.js:功能最全但體積大、已停止維護,新項目不推薦。
  • Luxon:現代 API、不可變、Intl 為基礎、支援時區。

常見陷阱與避坑

  1. 月份 0-11:getMonth() 返回 0-11,顯示需 +1。
  2. getYear() 已棄用:返回年份-1900,必須用 getFullYear()。
  3. 時區陷阱:new Date('2024-01-15') 視為 UTC,顯示為本地時間可能偏移一天。推薦 new Date(2024, 0, 15) (月份 0-based) 或指定時區字符串。
  4. 毫秒數溢出:JS Date 基於毫秒,安全範圍 ±100,000,000 天 (約 27 萬年)。
  5. 無效日期:new Date('invalid') 返回 Invalid Date,需 isNaN(date.getTime()) 判斷。
copyright © 萬盛學電腦網 all rights reserved