Date 物件是 JavaScript 中處理日期與時間的核心。建立物件後,可以取得年、月、日、時、分、秒等資訊,也能進行格式化輸出。
var d = new Date();需要注意的是,JavaScript 的月份從 0 開始,0 代表一月,11 代表十二月。
getFullYear、getMonth、getDate、getHours、getMinutes、getSeconds 常用來取得各項時間單位;getTime 則可取得從 1970 年 1 月 1 日以來的毫秒數。
Date.prototype.toString = function (format) {
var pad = function (n) {
return n < 10 ? "0" + n : n;
};
if (!format) {
return this.getFullYear() + "-" + pad(this.getMonth() + 1) + "-" + pad(this.getDate());
}
return format
.replace("yyyy", this.getFullYear())
.replace("MM", pad(this.getMonth() + 1))
.replace("dd", pad(this.getDate()))
.replace("HH", pad(this.getHours()))
.replace("mm", pad(this.getMinutes()))
.replace("ss", pad(this.getSeconds()));
};透過這種方式,就能把日期輸出成更符合介面需求的格式,例如 2024-01-05 或 14:30:00。