試一試
const event = new Date("August 19, 1975 23:15:30");
event.setDate(24);
console.log(event.getDate());
// Expected output: 24
event.setDate(32);
// Only 31 days in August!
console.log(event.getDate());
// Expected output: 1
語法
js
setDate(dateValue)
引數
dateValue-
一個表示月份中日期的整數。
返回值
該方法會原地修改 Date 物件,並返回其新的時間戳。如果 dateValue 是 NaN(或任何會被強制轉換為 NaN 的值,如 undefined),則日期將被設定為無效日期,並返回 NaN。
描述
如果您指定了一個超出預期範圍的數字,Date 物件中的日期資訊會相應地更新。例如,如果 Date 物件當前是 6 月 1 日,dateValue 為 40 會將日期更改為 7 月 10 日,而 dateValue 為 0 會將日期更改為上個月的最後一天,即 5 月 31 日。
由於 setDate() 是在本地時間操作的,穿越夏令時 (DST) 邊界可能會導致實際經過的時間與預期不同。例如,如果設定日期時穿越了春季向前調整(時鐘撥快一小時),新舊日期之間的時間戳差異將比名義上的日差(乘以 24 小時)少一個小時。反之,穿越秋季向後調整(時鐘撥慢一小時)會多出一個小時。如果您需要按固定的時間量調整日期,請考慮使用 setUTCDate() 或 setTime()。
如果新的本地時間落在偏移量轉換範圍內,則確切時間將使用與 Temporal 的 disambiguation: "compatible" 選項相同的行為來確定。也就是說,如果本地時間對應兩個瞬間,則選擇較早的那個;如果本地時間不存在(存在間隙),則向前推進間隙持續的時間。
示例
使用 setDate()
js
const theBigDay = new Date(1962, 6, 7, 12); // noon of 1962-07-07 (7th of July 1962, month is 0-indexed)
const theBigDay2 = new Date(theBigDay).setDate(24); // 1962-07-24 (24th of July 1962)
const theBigDay3 = new Date(theBigDay).setDate(32); // 1962-08-01 (1st of August 1962)
const theBigDay4 = new Date(theBigDay).setDate(22); // 1962-07-22 (22nd of July 1962)
const theBigDay5 = new Date(theBigDay).setDate(0); // 1962-06-30 (30th of June 1962)
const theBigDay6 = new Date(theBigDay).setDate(98); // 1962-10-06 (6th of October 1962)
const theBigDay7 = new Date(theBigDay).setDate(-50); // 1962-05-11 (11th of May 1962)
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-date.prototype.setdate |
瀏覽器相容性
載入中…