Date.prototype.getYear()

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 实例的 getYear() 方法根据当地时间返回该日期的年份。由于 getYear() 不返回完整年份 ("2000 年问题"),因此它已被弃用并已被 getFullYear() 方法取代。

¥The getYear() method of Date instances returns the year for this date according to local time. Because getYear() does not return full years ("year 2000 problem"), it is deprecated and has been replaced by the getFullYear() method.

语法

¥Syntax

js
getYear()

参数

¥Parameters

没有任何。

¥None.

返回值

¥Return value

一个整数,表示给定日期的年份(根据当地时间)减去 1900。如果日期是 invalid,则返回 NaN

¥An integer representing the year for the given date according to local time, minus 1900. Returns NaN if the date is invalid.

  • 对于大于或等于 2000 年的年份,该值为 100 或更大。例如,如果年份是 2026 年,则 getYear() 返回 126。
  • 对于 1900 年和 1999 年之间(含 1900 年和 1999 年)的年份,getYear() 返回的值介于 0 和 99 之间。例如,如果年份是 1976 年,则 getYear() 返回 76。
  • 对于小于 1900 的年份,getYear() 返回的值小于 0。例如,如果年份是 1800 年,则 getYear() 返回 -100。

该方法本质上返回 getFullYear() 减去 1900 的值。你应该使用 getFullYear() 来代替,以便完整指定年份。

¥This method essentially returns the value of getFullYear() minus 1900. You should use getFullYear() instead, so that the year is specified in full.

示例

¥Examples

1900 年至 1999 年

¥Years between 1900 and 1999

第二条语句将值 95 赋给变量 year

¥The second statement assigns the value 95 to the variable year.

js
const xmas = new Date("1995-12-25");
const year = xmas.getYear(); // returns 95

1999 年以上年份

¥Years above 1999

第二条语句将值 100 赋给变量 year

¥The second statement assigns the value 100 to the variable year.

js
const xmas = new Date("2000-12-25");
const year = xmas.getYear(); // returns 100

1900 年以下年份

¥Years below 1900

第二条语句将值 -100 赋给变量 year

¥The second statement assigns the value -100 to the variable year.

js
const xmas = new Date("1800-12-25");
const year = xmas.getYear(); // returns -100

设置和获取 1900 至 1999 之间的年份

¥Setting and getting a year between 1900 and 1999

第三条语句将值 95 赋给变量 year,代表 1995 年。

¥The third statement assigns the value 95 to the variable year, representing the year 1995.

js
const xmas = new Date("2015-12-25");
xmas.setYear(95);
const year = xmas.getYear(); // returns 95

规范

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

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看