Date.setFullYear() 方法是 JavaScript 中的一个内置函数,用于设置 Date 对象的 “year” 组件。此方法的返回值是 Date 对象的更新时间戳,它反映了通过修改年份所做的更改。或者,我们还可以修改 date 对象的 month 和 day 值。
如果传递给此方法的任何参数为 NaN 或未定义,则日期将设置为“无效日期”,并且将返回非数字 (NaN) 作为结果。
语法
以下是 JavaScript Date.setFullYear() 方法的语法 -
setFullYear(yearValue, monthValue, dateValue);
参数
此方法接受三个参数。下面描述相同 -
- yearValue − 整数表示新的一年(四位数字)。
- monthValue(可选)− 介于 0 和 11 之间的整数,其中 0 是 1 月,11 是 12 月。
- 如果提供 -1,则会导致上一年的最后一个月。
- 如果提供 12,则会导致明年的第一个月。
- dateValue(可选)− 介于 1 和 31 之间的整数。
- 如果提供 0,则为上个月的最后一天。
- 如果提供 -1,则结果将是上个月最后一天的前一天。
- 如果提供了 32,则结果将在下个月的第一天(如果该月有 31 天)。
- 如果提供了 32,则将在下个月的第二天(如果该月有 30 天)。
返回值
setFullYear() 方法在设置年份后返回更新的日期对象的时间戳。
示例 1
在以下示例中,我们使用 JavaScript Date.setFullYear()方法将 Date 对象的年份设置为 2023 -
<html>
<body>
<script>
const currentDate = new Date();
currentDate.setFullYear(2023);
document.write(currentDate);
</script>
</body>
</html>
输出
如果我们执行上述程序,年份将设置为 2023 年,月份和日期将根据当地时间。
示例 2
在这里,我们将年份设置为 (2023),将月份设置为 10(11 月),将日期设置为 (25) -
<html>
<body>
<script>
const specificDate = new Date();
specificDate.setFullYear(2023, 10, 25);
document.write(specificDate);
</script>
</body>
</html>
输出
执行后,此程序将返回包含所提供日期的时间戳。
示例 3
在此示例中,我们只更改年份,同时保持现有月份 (May) 和日期 (15) 不变。
<html>
<body>
<script>
const existingDate = new Date('2022-05-15');
existingDate.setFullYear(2023);
document.write(existingDate);
</script>
</body>
</html>
输出
它返回的时间戳为“Mon May 15, 2023 05:30:00 GMT+0530 (India Standard Time)”。
示例 4
如果我们为 monthValue 指定 “12”,则年份将递增 1 (yearValue + 1),并且 0 将用于该月。
<html>
<body>
<script>
const existingDate = new Date('2022-11-15'); //December 15 2022
existingDate.setFullYear(2022, 12, 15); // It will be January 15 2023
document.write(existingDate);
</script>
</body>
</html>
输出
它返回的时间戳为“Sun Jan 15, 2023 05:30:00 GMT+0530 (India Standard Time)”。
示例 5
如果我们为 dateValue 指定 “32”,则该月将递增 1(如果该月有 31 天),并将在下个月的第一天出现。
<html>
<body>
<script>
const existingDate = new Date('2023-10-30'); //October 2023 has 31 days.
existingDate.setFullYear(2023, 9, 32);
document.write(existingDate);
</script>
</body>
</html>
输出
它返回的时间戳为“Wed Nov 01, 2023 05:30:00 GMT+0530 (India Standard Time)”。
示例 6
如果我们将无效的日期值作为参数传递给此函数,则日期将设置为“无效日期”,并且返回“NaN”作为结果 -
<html>
<body>
<script>
const currentDate = new Date();
currentDate.setFullYear("dfbgf");
document.write(currentDate.getUTCFullYear());
</script>
</body>
</html>
输出
正如我们所看到的,“NaN” 作为输出返回。