DIV CSS 佈局教程網

js 日期插件 dateHelp:一次取得本月、近三個月、今年的日期區間
編輯:關於JavaScript     

做統計報表時,「本月」、「近三個月」、「今年」這幾個區間幾乎是必備的篩選條件。與其每個查詢畫面重寫一次日期計算,不如封裝成一個可重複使用的插件。本文用面向對象的思路寫了一個 DateHelp,直接 new 出來就能用。

使用方式

var myDate = new DateHelp({
  date: '2015-02-01',       // 從此日期開始計算
  format: 'yyyy/MM/dd'      // 輸出格式
});

myDate.getThisMonth();    // 本月區間
myDate.getThreeMonth();   // 近三個月區間
myDate.getThisYear();     // 今年區間

插件程式碼

/**
 * 取得本月、近三個月、今年的日期區間
 * @param obj
 * @constructor
 */
function DateHelp(obj) {
  this.date = obj.date;
  this.type = obj.type;
  this.value = obj.value == undefined ? obj.value : 0;
  this.format = obj.format == undefined ? obj.format : 'yyyy/MM/dd';

  // 統一取出年、月、日,同時相容 Date 物件與字串兩種傳入方式
  if (this.date instanceof Date) {
    this.year  = this.date.getFullYear();
    this.month = this.date.getMonth() + 1;
    this.day   = this.date.getDate();
  } else {
    this.year  = this.date.substr(0, 4);
    this.month = this.date.substr(5, 2);
    this.day   = this.date.substr(8, 2);
  }
}

// 往前推一段時間
DateHelp.prototype.beforeDate = function (type, value) {
  var _type  = type  || this.type,
      _value = value || this.value,
      _year  = this.year,
      _month = this.month,
      _day   = this.day;

  if (_type == 'year' || _type == '年') {
    _year -= _value;
  } else if (_type == 'month' || _type == '月') {
    _year  -= parseInt(_value / 12);
    _month -= _value % 12;
    if (_month <= 0) {
      _year -= 1;
      _month += 12;
    }
  }

  var date = new Date(_year, _month - 1, _day);
  return this.formatDate(date, this.format);
};

// 日期格式化
DateHelp.prototype.formatDate = function (date, fmt) {
  var 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+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? o[k] : (("00" + o[k]).substr(("" + o[k]).length)));
    }
  }
  return fmt;
};

// 本月:從 1 號到月末
DateHelp.prototype.getThisMonth = function () {
  var first = new Date(this.year, this.month - 1, 1);
  var last  = new Date(this.year, this.month, 0);   // 第 0 天就是上個月的最後一天
  return this.formatDate(first, this.format) + " - " + this.formatDate(last, this.format);
};

// 近三個月
DateHelp.prototype.getThreeMonth = function () {
  return this.beforeDate('month', 3) + " - " + this.beforeDate('day', 0);
};

// 今年:1/1 到 12/31
DateHelp.prototype.getThisYear = function () {
  var first = new Date(this.year, 0, 1);
  var last  = new Date(this.year, 11, 31);
  return this.formatDate(first, this.format) + " - " + this.formatDate(last, this.format);
};

HTML 測試頁

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>DateHelp 測試</title>
<script src="myJs/dateHelp.js"></script>
</head>
<body>
<script>
var myDate = new DateHelp({
  date: new Date(),      // 也可以傳入字串,例如 '2015-02-01'
  format: 'yyyy/MM/dd'
});
console.log(myDate.getThisMonth());
console.log(myDate.getThreeMonth());
console.log(myDate.getThisYear());
</script>
</body>
</html>

幾個值得記住的技巧與待修的小問題

月末日期怎麼算?程式裡的 new Date(this.year, this.month, 0) 是很值得記住的一招。JavaScript 的 Date 建構子會自動把溢出的日期進位,而「下一個月的第 0 天」正好等於「這個月的最後一天」,所以不必寫任何 if 判斷大小月,閏年二月也自動正確。

格式化裡的補零技巧。("00" + o[k]).substr(("" + o[k]).length) 靠字串補零再切出後兩位,一行就處理完所有需要兩位數的欄位,比一長串三元運算子乾淨。

不過原始程式有幾處必須修正才能正常運作:

第一,建構子裡的 this.value = obj.value == undefined ? obj.value : 0; 三元運算子的兩個分支寫反了——物件沒傳 value 時,應該給 0 而不是 undefined。

第二,getThisMonth() 的第一個日期少寫了「日」參數(new Date(year, month - 1)),雖然會預設為 1 號,但明確寫出 , 1 比較安全。

第三,beforeDate 裡的 'day' 分支是空的,因此 getThreeMonth() 中那個 this.beforeDate('day', 0) 會落到 formatDate 拿到未定義的日期。若要取得「今天」,直接 this.formatDate(new Date(), this.format) 即可。

第四,字串傳入時用 substr 硬切位置,這意味著輸入必須嚴格是 YYYY-MM-DD 這種固定格式;若可能是 2015-2-1 這類不補零的寫法就會切錯。改成 new Date(str.replace(/-/g, '/')) 再取各欄位會穩健得多。

以上就是本文所述,希望對大家學習 JavaScript 程式設計有所幫助。

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