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()
设置年份值的方式不同。具体来说,给定两位数,例如 22
和 61
:
¥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)
导致年份值设置为1922
,date.setYear(61)
导致年份值设置为1961
。(相比之下,虽然new Date(61, 1)
也会导致年份值设置为1961
,但new Date("2/1/22")
会导致年份值设置为2022
;对于Date.parse()
也类似)。setFullYear()
没有特殊解释,而是按原样使用文字两位数值来设置年份;因此date.setFullYear(61)
导致年份值设置为0061
,date.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.
语法
参数
返回值
¥Return value
就地更改 Date
对象,并返回其新的 timestamp。如果 yearValue
是 NaN
(或获取 coerced 到 NaN
的其他值,例如 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.
描述
示例
使用 setYear()
规范
Specification |
---|
ECMAScript Language Specification # sec-date.prototype.setyear |
浏览器兼容性
BCD tables only load in the browser