DIV CSS 佈局教程網

JavaScript 格式化日期物件的實用寫法
編輯:JavaScript綜合知識     

後端給的日期要顯示在頁面上,通常不會是 Mon Apr 17 2015 10:20:00 這種原始格式,而是 2015-04-17 10:20:00 這樣易讀的形式。本文提供一個直接的格式化函式,並說明幾個容易出錯的地方。

基本實作

/**
 * 把 Date 物件格式化為 "2015-04-17 10:20:00"
 * @param {Date} dateObj
 * @returns {String}
 */
function formartDate(dateObj){
  var updatetimeval =
      dateObj.getFullYear() + "-" +
      (dateObj.getMonth() + 1) + "-" +
      dateObj.getDate() + " " +
      dateObj.getHours() + ":" +
      dateObj.getMinutes() + ":" +
      dateObj.getSeconds();
  return updatetimeval;
}

兩個務必注意的地方

1. getMonth() 是從 0 開始的

這是最經典的陷阱:getMonth() 回傳 0 代表一月,11 代表十二月。所以必須 +1。忘了加,一月就會顯示成「0 月」。

2. 需要補零

上面的版本有個問題:4 月 7 日 9 點 5 分會輸出成 2015-4-7 9:5:0,看起來很凌亂,而且字串長度不一,不利於排序與比對。修正版如下:

function formatDate(dateObj){
  function pad(n){
    return n < 10 ? '0' + n : '' + n;
  }

  return dateObj.getFullYear() + '-' +
         pad(dateObj.getMonth() + 1) + '-' +
         pad(dateObj.getDate()) + ' ' +
         pad(dateObj.getHours()) + ':' +
         pad(dateObj.getMinutes()) + ':' +
         pad(dateObj.getSeconds());
}

console.log(formatDate(new Date()));   // 2015-04-07 09:05:00

順帶修正原函式的拼字:formartDate 應為 formatDate。這類拼字錯誤在程式碼中到處流傳,複製貼上時多留意。

更通用的寫法

實務上格式變化很多(2015/04/07、2015年4月7日、04-07 09:05…),寫死一個函式遲早不夠用。用一個格式字串參數會靈活得多:

function formatDate(date, fmt){
  fmt = fmt || 'yyyy-MM-dd HH:mm:ss';

  var map = {
    'yyyy': date.getFullYear(),
    'MM'  : date.getMonth() + 1,
    'dd'  : date.getDate(),
    'HH'  : date.getHours(),
    'mm'  : date.getMinutes(),
    'ss'  : date.getSeconds()
  };

  return fmt.replace(/yyyy|MM|dd|HH|mm|ss/g, function(m){
    var v = map[m];
    return m.length === 2 ? String(v).padStart(2, '0') : v;
  });
}

console.log(formatDate(new Date(), 'yyyy/MM/dd'));       // 2015/04/07
console.log(formatDate(new Date(), 'yyyy年MM月dd日'));   // 2015年04月07日

時區問題不能忽略

如果日期來自伺服器(例如 "2015-04-17T02:20:00Z" 這種 UTC 時間),直接 new Date(str) 後格式化,顯示的會是使用者當地的時間。這通常是我們想要的,但前後端如果沒有共識,就會出現「資料庫存 8 小時前,畫面顯示 8 小時後」這類離奇的 bug。實務上建議整個團隊統一的策略:要嘛全部用 UTC 傳輸並在前端轉換,要嘛全部用帶時區的 ISO 8601 格式。

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