DIV CSS 佈局教程網

擴充 Date:用自訂 format 格式化時間的實作
編輯:JavaScript綜合知識     

JavaScript 原生的 Date 物件並沒有內建的格式化方法。透過擴充 Date.prototype,我們可以自訂一個 format 函式,用類似 yyyy-MM-dd hh:mm:ss 的字串樣板,輕鬆輸出想要的日期格式。

格式化方法

/**
 * 時間物件格式化
 * eg: format = "YYYY-MM-dd hh:mm:ss"
 */
Date.prototype.format = function (format) {
  var o = {
    "M+": this.getMonth() + 1,          // month
    "d+": this.getDate(),               // day
    "h+": this.getHours(),              // hour
    "m+": this.getMinutes(),            // minute
    "s+": this.getSeconds(),            // second
    "q+": Math.floor((this.getMonth() + 3) / 3), // quarter
    "S":  this.getMilliseconds()        // millisecond
  };
  if (/(y+)/.test(format)) {
    format = format.replace(RegExp.$1,
      (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(format)) {
      format = format.replace(RegExp.$1,
        RegExp.$1.length == 1 ? o[k] :
        ("00" + o[k]).substr(("" + o[k]).length));
    }
  }
  return format;
};

使用範例

// 完整格式
var now = new Date().format("yyyy-MM-dd hh:mm:ss");

// 省略秒數、年份縮寫
new Date().format("yy-MM-dd hh:mm");

原理說明

這個方法先建立一個對照表 o,把「月、日、時、分、秒、季度、毫秒」等欄位取出來。接著用正則比對樣板:遇到 y 就換成年份,其餘欄位則逐一比對並替換。當樣板中的符號大於一位時,還會用 ("00" + 值).substr(...) 補零對齊,讓輸出如 09 這樣美觀。理解這個「查表+正則替換」的套路後,你就能自由擴充更多自訂欄位。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved