把 Date 物件輸出成「2015-04-17 10:20:00」這樣的字串,是後端串接與報表匯出時的常見需求。
/* 將 Date 物件格式化為 "2015-04-17 10:20:00" */
function formartDate(dateObj) {
var updatetimeval = dateObj.getFullYear() + "-" +
(dateObj.getMonth() + 1) + "-" + dateObj.getDate() + " " +
dateObj.getHours() + ":" + dateObj.getMinutes() + ":" + dateObj.getSeconds();
return updatetimeval;
}
這個版本能動,但有個明顯問題:沒有補零。一月會輸出成 "2015-1-5" 而不是 "2015-01-05",在排序、比對或交給 expects 固定格式的 API 時都會出錯。補零是很基本卻經常被忽略的細節。
改良版本如下:
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())); // 2026-08-19 17:14:08
幾個容易踩到的重點值得記住:
getMonth() 從 0 起算。這是所有日期 API 中最常見的錯誤來源,取月份一定要 +1,取星期則是 0 代表週日。
注意時區。getFullYear()/getHours() 這組讀的是「本地時間」;若你需要 UTC,要用 getUTCFullYear()/getUTCHours()。跨時區的系統若混用兩者,會出現難以察覺的八小時偏差。
ES6 之後有更簡潔的寫法。若環境允許,Intl.DateTimeFormat 或 toLocaleString 都能直接輸出格式化結果;而 toISOString() 會給出標準的 UTC 格式字串(2026-08-19T09:14:08.000Z),是與後端溝通時最不容易出錯的選擇。若需要更多格式模板,也可考慮成熟的日期函式庫,避免自己維護一堆格式字串。