DIV CSS 佈局教程網

處理 MVC 回傳的 /Date(1000000000)/ 時間格式
編輯:關於JavaScript     

在 MVC 專案中,以 POST 取回的 JSON 內若包含 DateTime 欄位,序列化後常會變成 /Date(1000000000)/ 這種難以直接使用的格式。上網找的方法多不完整,因此這裡整理成一個 jQuery 外掛,方便重複使用。

外掛程式碼

(function ($) {

  /**
   * 將 /Date(1000000000)/ 轉為自訂格式的字串
   * @param dtstr JSON 中的日期字串
   * @param fmt   目標格式,如 'yyyy-MM-dd hh:mm:ss'
   */
  $.Format = function (dtstr, fmt) {
    var date = $.ToDateTime(dtstr);
    if (!date) { return ''; }

    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;
  };

  /** 把 /Date(1000000000)/ 或 'yyyy-MM-ddTHH:mm:ss' 轉成 Date 物件 */
  $.ToDateTime = function (dtstr) {
    var s = dtstr + '';
    if (s.indexOf('Date(') >= 0) {
      var ldate = +s.replace('/Date(', '').replace(')/', '');
      if (ldate > 0) { return new Date(ldate); }
    } else {
      var str = s.replace(/-/g, "/").replace(/T/g, " ");
      if (str.split('.')[0] == '1900/01/01 00:00:00') {
        return null;                       // .NET 的 DateTime.MinValue 視為空
      }
      if (s.length > 0) { return new Date(str.split('.')[0]); }
    }
    return null;
  };

})(jQuery);

使用方式

先引入上述外掛,接著在 Ajax 回呼中格式化時間欄位:

$.post("/tigger/GetUserPrizeLog?t=" + Math.random(),
  { activityCode: 1138, myOpenId: "@WorkContext.WxUserInfo.OpenId" },
  function (json) {
    var str = "";
    $.each(json.Body, function (i, model) {
      str += "<li>";
      str += "<p class=\"title\">" + model.ActivityPrizeName + "</p>";
      str += "<p class=\"time\">" + $.Format(model.CreateTime, "yyyy-MM-dd hh:mm") + "</p>";
      str += "<span class=\"get\" onclick=\"ShowPrize('" + model.ActivityPrizeName + "')\"></span>";
      str += "</li>";
    });
    $("#record ul").html(str);
  });

其中 model.CreateTime 就是伺服器端傳回的時間欄位,透過 $.Format(model.CreateTime, "yyyy-MM-dd hh:mm") 即可輸出成易讀格式。

幾個實務建議

  • 最佳解法其實在後端:於伺服器端就把日期格式化為字串,或使用 ISO 8601 格式輸出,前端就不必額外處理時區問題。
  • 時區要注意:/Date(...)/ 存的是 UTC 毫秒數,直接 new Date 後顯示的會是使用者當地的時間,若前後端時區假設不同就會產生落差。
  • 避免用字串拼接 HTML:範例中的 ShowPrize('...') 若資料含單引號會直接破壞語法,正式環境建議改用事件綁定與 text() 設定文字。
  • 若專案已引入 moment.js 或 day.js,直接用其格式化功能會比自製外掛更省事也更可靠。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved