DIV CSS 佈局教程網

JavaScript 日期格式化方法
編輯:關於JavaScript     

日期格式化是前端常見需求。可以擴充 Date.prototype,讓 Date 物件直接轉為指定格式的字串。

常用格式

例如 yyyy-MM-dd hh:mm:ss,可輸出年、月、日、時、分、秒。若需要毫秒或季度,也可加入對應規則。

Date.prototype.format = function (fmt) {
  var o = {
    "M+": this.getMonth() + 1,
    "d+": this.getDate(),
    "h+": this.getHours(),
    "m+": this.getMinutes(),
    "s+": this.getSeconds()
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (this.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;
};

使用時可直接呼叫:

new Date().format("yyyy-MM-dd hh:mm:ss");

這種做法簡單直覺,但正式專案中也可考慮 date-fns、dayjs 等函式庫,以減少自行維護格式字元的成本。

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