萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 日期物件格式化為「YYYY-MM-DD HH:mm:ss」字串函式

常用格式化函式

將 Date 物件格式化為標準字串格式(如 2015-04-17 10:20:00)的實用函式:

/**
 * 格式化 Date 物件為 "YYYY-MM-DD HH:mm:ss"
 * @param {Date} dateObj - 日期物件
 * @returns {String} 格式化後字串
 */
function formartDate(dateObj) {
  var year = dateObj.getFullYear();
  var month = dateObj.getMonth() + 1; // 月份從 0 開始
  var day = dateObj.getDate();
  var hours = dateObj.getHours();
  var minutes = dateObj.getMinutes();
  var seconds = dateObj.getSeconds();

  // 補零輔助函式
  var pad = function(n) { return n < 10 ? '0' + n : n; };

  return year + '-' + pad(month) + '-' + pad(day) + ' ' +
         pad(hours) + ':' + pad(minutes) + ':' + pad(seconds);
}

// 使用範例
var now = new Date();
console.log(formartDate(now)); // 輸出如 "2024-01-15 14:30:05"

進階版:支援自訂格式模板

若需更靈活的格式(如 YYYY/MM/DD、HH:mm 等),可參考以下擴充版本:

Date.prototype.format = function(fmt) {
  var o = {
    "M+": this.getMonth() + 1,
    "d+": this.getDate(),
    "h+": this.getHours(),
    "m+": this.getMinutes(),
    "s+": this.getSeconds(),
    "q+": Math.floor((this.getMonth() + 3) / 3),
    "S": this.getMilliseconds()
  };
  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;
};

// 使用範例
var d = new Date();
console.log(d.format("yyyy-MM-dd hh:mm:ss")); // 2024-01-15 14:30:05
console.log(d.format("yyyy/MM/dd"));          // 2024/01/15

建議專案中統一使用格式化函式,避免手動拼接字串導致月份、小時未補零等常見錯誤。

copyright © 萬盛學電腦網 all rights reserved