此頁面由社群從英文翻譯而來。了解更多並加入 MDN Web Docs 社群。

View in English Always switch to English

Date.prototype.setUTCHours()

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 實例的 setUTCHours() 方法會根據世界協調時間變更此日期的時、分、秒及/或毫秒。

嘗試一下

const event = new Date("August 19, 1975 23:15:30 GMT-3:00");

console.log(event.toUTCString());
// 預期輸出:「Wed, 20 Aug 1975 02:15:30 GMT」

console.log(event.getUTCHours());
// 預期輸出:2

event.setUTCHours(23);

console.log(event.toUTCString());
// 預期輸出:「Wed, 20 Aug 1975 23:15:30 GMT」

語法

js
setUTCHours(hoursValue)
setUTCHours(hoursValue, minutesValue)
setUTCHours(hoursValue, minutesValue, secondsValue)
setUTCHours(hoursValue, minutesValue, secondsValue, msValue)

參數

hoursValue

一個介於 0 到 23 之間的整數,表示小時。

minutesValue 選擇性

一個介於 0 到 59 之間的整數,表示分鐘。

secondsValue 選擇性

一個介於 0 到 59 之間的整數,表示秒。若你指定 secondsValue,則必須同時指定 minutesValue

msValue 選擇性

一個介於 0 到 999 之間的整數,表示毫秒。若你指定 msValue,則必須同時指定 minutesValuesecondsValue

回傳值

就地更改 Date 物件,並回傳其新的時間戳。若參數為 NaN(或其他會被強制轉型NaN 的值,例如 undefined),則日期會被設為無效日期,並回傳 NaN

描述

若你沒有指定 minutesValuesecondsValuemsValue 參數,將會使用 getUTCMinutes()getUTCSeconds()getUTCMilliseconds() 方法回傳的值。

若你指定的參數超出預期範圍,setUTCHours() 會相應地嘗試更新 Date 物件中的日期訊息。例如,若你為 secondsValue 指定 100,則分鐘數會增加 1(minutesValue + 1),而秒數則會使用 40。

範例

使用 setUTCHours()

js
const theBigDay = new Date();
theBigDay.setUTCHours(8);

規範

Specification
ECMAScript® 2026 Language Specification
# sec-date.prototype.setutchours

瀏覽器相容性

參見