Date.prototype.setDate()

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

setDate() 方法Date 实例用于在本地时间更改此日期的月份中的日期。

试一试

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 对象,并返回其新的时间戳。如果 dateValueNaN(或任何会被强制转换为 NaN 的值,如 undefined),则日期将被设置为无效日期,并返回 NaN

描述

如果您指定了一个超出预期范围的数字,Date 对象中的日期信息会相应地更新。例如,如果 Date 对象当前是 6 月 1 日,dateValue 为 40 会将日期更改为 7 月 10 日,而 dateValue 为 0 会将日期更改为上个月的最后一天,即 5 月 31 日。

由于 setDate() 是在本地时间操作的,穿越夏令时 (DST) 边界可能会导致实际经过的时间与预期不同。例如,如果设置日期时穿越了春季向前调整(时钟拨快一小时),新旧日期之间的时间戳差异将比名义上的日差(乘以 24 小时)少一个小时。反之,穿越秋季向后调整(时钟拨慢一小时)会多出一个小时。如果您需要按固定的时间量调整日期,请考虑使用 setUTCDate()setTime()

如果新的本地时间落在偏移量转换范围内,则确切时间将使用与 Temporaldisambiguation: "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

浏览器兼容性

另见