Date.prototype.setYear()
The legacy setYear()
method sets the year for a specified date according to local time.
However, the way the legacy setYear()
method sets year values is different from how the preferred Date.prototype.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()
interprets any two-digit number as an offset to1900
; sodate.setYear(22)
results in the year value being set to1922
, anddate.setYear(61)
results in the year value being set to1961
. (In contrast, whilenew Date(61, 1)
also results in the year value being set to1961
,new Date("2/1/22")
results in the year value being set to2022
; and similarly forDate.parse()
).Date.prototype.setFullYear()
does no special interpretation but instead uses the literal two-digit value as-is to set the year; sodate.setFullYear(61)
results in the year value being set to0061
, anddate.setFullYear(22)
results in the year value being set to0022
.
Because of those differences in behavior, you should no longer use the legacy setYear()
method, but should instead use the preferred Date.prototype.setFullYear()
method.
Syntax
setYear(yearValue)
Parameters
yearValue
- : An integer.
Return value
The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date.
Description
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
.