Date.prototype.setTime()
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2015年7月.
Date
實例的 setTime()
方法會變更此日期的時間戳,也就是自紀元(定義為 UTC 1970 年 1 月 1 日午夜)起算的毫秒數。
嘗試一下
const launchDate = new Date("July 1, 1999, 12:00:00");
const futureDate = new Date();
futureDate.setTime(launchDate.getTime());
console.log(futureDate);
// 預期輸出:「Thu Jul 01 1999 12:00:00 GMT+0200 (CEST)」
const fiveMinutesInMs = 5 * 60 * 1000;
futureDate.setTime(futureDate.getTime() + fiveMinutesInMs);
console.log(futureDate);
// 預期輸出:「Thu Jul 01 1999 12:05:00 GMT+0200 (CEST)」
// 備註:你的時區可能會有所不同
語法
js
setTime(timeValue)
參數
timeValue
-
一個表示新時間戳的整數——即自 UTC 1970 年 1 月 1 日午夜起算的毫秒數。
回傳值
就地變更 Date
物件,並回傳其新的時間戳。如果 timeValue
是 NaN
(或其他會被強制轉換為 NaN
的值,例如 undefined
),則日期會被設定為無效日期,並回傳 NaN
。
範例
>使用 setTime()
js
const theBigDay = new Date("1999-07-01");
const sameAsBigDay = new Date();
sameAsBigDay.setTime(theBigDay.getTime());
規範
Specification |
---|
ECMAScript® 2026 Language Specification> # sec-date.prototype.settime> |
瀏覽器相容性
Loading…