萬盛學電腦網

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

JavaScript 日期格式化工具函數:高性能、擴展性強的最佳實踐

日期格式化是高頻需求。本文提供兩個生產級工具函數:parseToDate (時間戳→格式化字符串) 與 formatDate (Date 對象→格式化字符串),支持自定義模板、零填充、毫秒級精度。

核心實現

var Util = (function() {
  // 私有:零填充輔助
  function pad(num, len) {
    var s = '0000' + num;
    return s.substr(s.length - (len || 2));
  }

  // 核心格式化引擎
  function format(date, pattern) {
    var y = date.getFullYear();
    var M = date.getMonth() + 1;
    var d = date.getDate();
    var h = date.getHours();
    var m = date.getMinutes();
    var s = date.getSeconds();
    var S = date.getMilliseconds();
    
    return pattern
      .replace('yyyy', y)
      .replace('yy', pad(y % 100))
      .replace('MM', pad(M))
      .replace('M', M)
      .replace('dd', pad(d))
      .replace('d', d)
      .replace('HH', pad(h))
      .replace('H', h)
      .replace('hh', pad(h % 12 || 12)) // 12小時制
      .replace('h', h % 12 || 12)
      .replace('mm', pad(m))
      .replace('m', m)
      .replace('ss', pad(s))
      .replace('s', s)
      .replace('SSS', pad(S, 3))
      .replace('S', S)
      .replace('A', h >= 12 ? 'PM' : 'AM')
      .replace('a', h >= 12 ? 'pm' : 'am');
  }

  return {
    // 時間戳(毫秒) → 格式化字符串
    parseToDate: function(ms, pattern) {
      return format(new Date(parseInt(ms)), pattern || 'yyyy-MM-dd HH:mm');
    },
    
    // Date 對象 → 格式化字符串
    formatDate: function(date, pattern) {
      return format(date instanceof Date ? date : new Date(date), pattern || 'yyyy-MM-dd HH:mm');
    }
  };
})();

使用示例

// 時間戳轉換
console.log(Util.parseToDate(Date.now()));           // "2024-01-15 14:30"
console.log(Util.parseToDate(1705300200000, 'yyyy/MM/dd HH:mm:ss')); 

// Date 對象格式化
var now = new Date();
console.log(Util.formatDate(now, 'yyyy年MM月dd日'));     // "2024年01月15日"
console.log(Util.formatDate(now, 'HH:mm:ss.SSS'));       // "14:30:45.123"
console.log(Util.formatDate(now, 'yyyy-MM-ddTHH:mm:ss')); // ISO-like "2024-01-15T14:30:45"

// 常用模板常量
Util.FORMATS = {
  DATETIME: 'yyyy-MM-dd HH:mm:ss',
  DATE: 'yyyy-MM-dd',
  TIME: 'HH:mm:ss',
  ISO: 'yyyy-MM-ddTHH:mm:ss',
  CN: 'yyyy年MM月dd日 HH:mm'
};

console.log(Util.formatDate(new Date(), Util.FORMATS.CN));

性能優化版:預編譯正則 (高頻調用場景)

var DateFormatter = (function() {
  var tokens = {
    yyyy: 'getFullYear',
    yy: function(d) { return pad(d.getFullYear() % 100); },
    MM: function(d) { return pad(d.getMonth() + 1); },
    M: function(d) { return d.getMonth() + 1; },
    dd: function(d) { return pad(d.getDate()); },
    d: function(d) { return d.getDate(); },
    HH: function(d) { return pad(d.getHours()); },
    H: function(d) { return d.getHours(); },
    hh: function(d) { var h = d.getHours() % 12; return pad(h || 12); },
    h: function(d) { var h = d.getHours() % 12; return h || 12; },
    mm: function(d) { return pad(d.getMinutes()); },
    m: function(d) { return d.getMinutes(); },
    ss: function(d) { return pad(d.getSeconds()); },
    s: function(d) { return d.getSeconds(); },
    SSS: function(d) { return pad(d.getMilliseconds(), 3); },
    S: function(d) { return d.getMilliseconds(); },
    A: function(d) { return d.getHours() >= 12 ? 'PM' : 'AM'; },
    a: function(d) { return d.getHours() >= 12 ? 'pm' : 'am'; }
  };

  // 預編譯 token 正則
  var tokenRegex = new RegExp(Object.keys(tokens).sort((a,b) => b.length - a.length).join('|'), 'g');

  return function(date, pattern) {
    return String(pattern).replace(tokenRegex, function(match) {
      var token = tokens[match];
      return typeof token === 'function' ? token(date) : date[token]();
    });
  };
})();

現代原生替代:Intl.DateTimeFormat

// 零依賴、瀏覽器原生、支持多語言
function formatModern(date, locale = 'zh-CN', options = {}) {
  const defaultOpts = {
    year: 'numeric', month: '2-digit', day: '2-digit',
    hour: '2-digit', minute: '2-digit', second: '2-digit',
    hour12: false
  };
  return new Intl.DateTimeFormat(locale, {...defaultOpts, ...options}).format(date);
}

console.log(formatModern(new Date())); 
// "2024/01/15 14:30:45" (zh-CN)
// "01/15/2024, 2:30:45 PM" (en-US)

避坑指南

  1. 月份 0-based:getMonth() 返回 0-11,顯示需 +1。
  2. getYear() 已棄用:返回年份-1900,必須用 getFullYear()。
  3. 時區陷阱:new Date('2024-01-15') 解析為 UTC,顯示可能偏移。推薦 new Date(2024, 0, 15) (參數為本地時間)。
  4. 毫秒精度:JS Date 精度為毫秒,Date.now() 返回毫秒時間戳。

推薦策略:簡單場景用 Intl.DateTimeFormat;需高度自定義模板、極致性能、或舊環境兼容時,使用上述預編譯版工具函數。

copyright © 萬盛學電腦網 all rights reserved