DIV CSS 佈局教程網

JavaScript 的 Date 日期物件擴充:加減運算與自訂格式化
編輯:JavaScript基礎知識     

一、前言

JavaScript 的 Date 物件提供了大量日期屬性與操作方法,為網站開發帶來不少便利。然而實際上,絕大多數頁面要展示給使用者的日期格式是 yyyy-MM-dd hh:mm:ss(類似 C#、Java 的 ToString())。

問題就在這裡:不論是 Date 的 toString(),還是 toGMTString()、toISOString()、toLocaleDateString(),都無法直接產出我們日常想要的格式;而日期的加減運算,Date 物件同樣沒有提供現成的封裝。

那麼需要進行日期運算時該怎麼辦?最實際的做法就是自己動手,把常用的日期處理函式封裝起來。以下是我在開發過程中累積的一些簡單而實用的擴充,未來也會持續補充、優化。

二、程式碼

// 名稱:日期加法函式
// 參數:part(year、month、day、hour、minute、second、millisecond)
// 回傳:Date 物件
Date.prototype.add = function (part, value) {
  if (!value || isNaN(value)) value = 0;
  switch (part) {
    case "year":        this.setFullYear(this.getFullYear() + value); break;
    case "month":       this.setMonth(this.getMonth() + value); break;
    case "day":         this.setDate(this.getDate() + value); break;
    case "hour":        this.setHours(this.getHours() + value); break;
    case "minute":      this.setMinutes(this.getMinutes() + value); break;
    case "second":      this.setSeconds(this.getSeconds() + value); break;
    case "millisecond": this.setMilliseconds(this.getMilliseconds() + value); break;
    default:
  }
  return this;
};

Date.prototype.addYears        = function (value) { if (!value || isNaN(value)) value = 0; this.setFullYear(this.getFullYear() + value); return this; };
Date.prototype.addMonths       = function (value) { if (!value || isNaN(value)) value = 0; this.setMonth(this.getMonth() + value); return this; };
Date.prototype.addDays         = function (value) { if (!value || isNaN(value)) value = 0; this.setDate(this.getDate() + value); return this; };
Date.prototype.addHours        = function (value) { if (!value || isNaN(value)) value = 0; this.setHours(this.getHours() + value); return this; };
Date.prototype.addMinutes      = function (value) { if (!value || isNaN(value)) value = 0; this.setMinutes(this.getMinutes() + value); return this; };
Date.prototype.addSeconds      = function (value) { if (!value || isNaN(value)) value = 0; this.setSeconds(this.getSeconds() + value); return this; };
Date.prototype.addMilliseconds = function (value) { if (!value || isNaN(value)) value = 0; this.setMilliseconds(this.getMilliseconds() + value); return this; };

// 名稱:時間加法函式
// 參數:time(時間字串,示例:12:00:00)
// 回傳:Date 物件
Date.prototype.addTime = function (time) {
  var timeRegex = /^([0-1]?\d|2[0-3])(:[0-5]?\d){1,2}$/g;
  if (timeRegex.test(time)) {
    var value = Date.parse("1970/1/1 " + time) - Date.parse("1970/1/1");
    this.setMilliseconds(this.getMilliseconds() + value);
  }
  return this;
};

// 名稱:日期格式化函式
// 參數:format(示例:yyyy-MM-dd hh:mm:ss)、zeroize(是否補零)
// 回傳:日期字串
Date.prototype.toCustomString = function (format, zeroize) {
  if (!zeroize) zeroize = false;

  var dy = this.getFullYear();
  var dM = this.getMonth() + 1;
  var dd = this.getDate();
  var dh = this.getHours();
  var dm = this.getMinutes();
  var ds = this.getSeconds();
  var dS = this.getMilliseconds();

  var orm = {
    "y+": dy.toString(),
    "M+": !zeroize ? dM.toString() : dM < 10 ? '0' + dM : dM.toString(),
    "d+": !zeroize ? dd.toString() : dd < 10 ? '0' + dd : dd.toString(),
    "h+": !zeroize ? dh.toString() : dh < 10 ? '0' + dh : dh.toString(),
    "m+": !zeroize ? dm.toString() : dm < 10 ? '0' + dm : dm.toString(),
    "s+": !zeroize ? ds.toString() : ds < 10 ? '0' + ds : ds.toString(),
    "S":  dS.toString()
  };

  for (var i in orm) {
    var patt = new RegExp(i);
    if (patt.test(format)) {
      var item = orm[i];
      var ms = format.match(patt);
      var result = ms[0];
      if (i === "S") {
        format = format.replace(result, item);
      } else {
        // 依佔位符長度,從右側截取對應位數
        format = format.replace(result, item.substr(item.length - result.length));
      }
    }
  }
  return format;
};

三、解析

1. add 函式:第一個參數指定要運算的日期部分(年、月、日、時、分、秒、毫秒),回傳日期物件本身,因此可以用來串接。

2. add## 函式:addYears、addMonths、addDays 這一系列,其實就是 add 的分解版,目的是讓常見場景呼叫起來更直覺。

3. addTime 函式:提供「日期物件 + 時間字串」的運算能力,time 參數形如 10:00:00。實作上先用正則驗證格式,再透過兩個零時間點的差值換算出毫秒數。

4. toCustomString 函式:把日期物件轉成指定格式的字串。format 為格式字串(示例:yyyy-MM-dd hh:mm:ss);zeroize 決定月、日、時、分、秒是否補零。

以下示例中,前兩例示範 add 與 add## 的用法,第三例示範 addTime,三例都用 toCustomString 格式化輸出:

// 示例 1:d1 為整數型,表示毫秒數
var d1 = Date.now();
var ret1 = new Date(d1).add("year", 2); // 亦可寫成 new Date(d1).addYears(2)
console.log(ret1.toCustomString("yyyy-MM-dd hh:mm:ss")); // 2018-3-28 19:15:45

// 示例 2:d2 為字串型日期
var d2 = "2016-1-1 12:00:00";
var ret2 = new Date(Date.parse(d2)).add("day", 10); // 亦可寫成 .addDays(10)
console.log(ret2.toCustomString("yyyy/MM/dd hh時mm分ss秒", true)); // 2016/01/11 12時00分00秒

// 示例 3:日期型與時間字串型的運算
var ret3 = new Date(Date.now()).addTime("2:10:00");
console.log(ret3.toCustomString("yyyy-MM-dd hh:mm:ss", true)); // 2016-03-28 21:25:45

最後提醒一個實務上的注意事項:直接擴充 Date.prototype 雖然呼叫起來順手,但屬於修改內建物件,在多人協作或引入第三方庫時容易與他人擴充同名方法而衝突。若專案規模較大,建議改寫成獨立的工具函式(例如 dateAdd(date, part, value)),或以符號、命名空間隔離,會更穩妥。另外 ES2015 之後的 Intl.DateTimeFormat 與 toLocaleString 的 options 參數,已經能應付大部分格式化需求,可以優先評估。

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