Date.prototype.setYear()

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

Date 实例的 setYear() 方法根据当地时间设置指定日期的年份。

¥The setYear() method of Date instances sets the year for a specified date according to local time.

但是,旧 setYear() 方法设置年份值的方式与首选 setFullYear() 方法设置年份值的方式不同,并且在某些情况下,也与 new Date()Date.parse() 设置年份值的方式不同。具体来说,给定两位数,例如 2261

¥However, the way the legacy setYear() method sets year values is different from how the preferred setFullYear() method sets year values — and in some cases, also different from how new Date() and Date.parse() set year values. Specifically, given two-digit numbers, such as 22 and 61:

  • setYear() 将任何两位数字解释为 1900 的偏移量;因此 date.setYear(22) 导致年份值设置为 1922date.setYear(61) 导致年份值设置为 1961。(相比之下,虽然 new Date(61, 1) 也会导致年份值设置为 1961,但 new Date("2/1/22") 会导致年份值设置为 2022;对于 Date.parse() 也类似)。
  • setFullYear() 没有特殊解释,而是按原样使用文字两位数值来设置年份;因此 date.setFullYear(61) 导致年份值设置为 0061date.setFullYear(22) 导致年份值设置为 0022

由于这些行为差异,你不应再使用旧版 setYear() 方法,而应使用首选 setFullYear() 方法。

¥Because of those differences in behavior, you should no longer use the legacy setYear() method, but should instead use the preferred setFullYear() method.

语法

¥Syntax

js
setYear(yearValue)

参数

¥Parameters

yearValue

一个整数。

返回值

¥Return value

就地更改 Date 对象,并返回其新的 timestamp。如果 yearValueNaN(或获取 coercedNaN 的其他值,例如 undefined),则日期设置为 失效日期 并返回 NaN

¥Changes the Date object in place, and returns its new timestamp. If yearValue is NaN (or other values that get coerced to NaN, such as undefined), the date is set to Invalid Date and NaN is returned.

描述

¥Description

如果 yearValue 是 0 到 99(含)之间的数字,则 dateObj 的年份设置为 1900 + yearValue。否则,dateObj 的年份设置为 yearValue

¥If yearValue is a number between 0 and 99 (inclusive), then the year for dateObj is set to 1900 + yearValue. Otherwise, the year for dateObj is set to yearValue.

示例

¥Examples

使用 setYear()

¥Using setYear()

前两行将年份设置为 1996 年。第三个将年份设置为 2000 年。

¥The first two lines set the year to 1996. The third sets the year to 2000.

js
const theBigDay = new Date();

theBigDay.setYear(96);
theBigDay.setYear(1996);
theBigDay.setYear(2000);

规范

Specification
ECMAScript Language Specification
# sec-date.prototype.setyear

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看