getTime() 是 JavaScript Date 物件的核心方法,用於返回自 1970 年 1 月 1 日 00:00:00 UTC(Unix 紀元)以來經過的毫秒數。這個整數值是進行日期時間運算、比較與儲存的基礎。
dateObj.getTime()
參數: dateObj — 必選,任一 Date 物件實例。
Date 物件所表示時間的毫秒差。在進行日期換算時,預先定義常用毫秒常數能大幅簡化程式碼:
const MinMilli = 1000 * 60; // 一分鐘毫秒數
const HrMilli = MinMilli * 60; // 一小時毫秒數
const DyMilli = HrMilli * 24; // 一天毫秒數
function getDaysSinceEpoch() {
const now = new Date();
const msPerDay = 24 * 60 * 60 * 1000;
const days = Math.round(now.getTime() / msPerDay);
return `距離 1970/01/01 已經過 ${days} 天`;
}
console.log(getDaysSinceEpoch());