JS date getYear()

🌙
手机阅读
本文目录结构

已废弃
该特性已经从 Web 标准中删除,虽然一些浏览器目前仍然支持它,但也许会在未来的某个时间停止支持,请尽量不要使用该特性。

getYear() 方法返回指定的本地日期的年份。因为 getYear 不返回千禧年[full years] (“year 2000 problem”),所以这个方法不再被使用,现在替换为 getFullYear .

Syntax

dateObj.getYear() 

Parameters

None.

Returns

The getYear method returns the year minus 1900; thus:

  • For years greater than or equal to 2000, the value returned by getYear is 100 or greater. For example, if the year is 2026, getYear returns 126.
  • For years between and including 1900 and 1999, the value returned by getYear is between 0 and 99. For example, if the year is 1976, getYear returns 76.
  • For years less than 1900, the value returned by getYear is less than 0. For example, if the year is 1800, getYear returns -100.

To take into account years before and after 2000, you should use getFullYear() instead of getYear so that the year is specified in full.

Backward Compatibility

Behaviour in JavaScript 1.2 and earlier

The getYear method returns either a 2-digit or 4-digit year:

  • For years between and including 1900 and 1999, the value returned by getYear is the year minus 1900. For example, if the year is 1976, the value returned is 76.
  • For years less than 1900 or greater than 1999, the value returned by getYear is the four-digit year. For example, if the year is 1856, the value returned is 1856. If the year is 2026, the value returned is 2026.

Examples

Example: Years between 1900 and 1999

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

var Xmas = new Date("December 25, 1995 23:15:00");
var year = Xmas.getYear(); // returns 95

Example: Years above 1999

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

var Xmas = new Date("December 25, 2000 23:15:00");
var year = Xmas.getYear(); // returns 100

Example: Years below 1900

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

var Xmas = new Date("December 25, 1800 23:15:00");
var year = Xmas.getYear(); // returns -100

Example: Setting and getting a year between 1900 and 1999

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

var Xmas.setYear(95);
var year = Xmas.getYear(); // returns 95 

Specifications

Specification Status Comment
ECMAScript 1st Edition. Implemented in JavaScript 1.0 Standard Initial definition.
ECMAScript 5.1 (ECMA-262) Date.prototype.getYear Standard Defined in the (informative) compatibility annex.
ECMAScript 2015 (6th Edition, ECMA-262)Date.prototype.getYear Standard Defined in the (normative) annex for additional features for web browsers.

See also

AXIHE / 精选资源

浏览全部教程

面试题

学习网站

前端培训
自己甄别

前端书籍

关于朱安邦

我叫 朱安邦,阿西河的站长,在杭州。

以前是一名平面设计师,后来开始接接触前端开发,主要研究前端技术中的JS方向。

业余时间我喜欢分享和交流自己的技术,欢迎大家关注我的 Bilibili

关注我: Github / 知乎

于2021年离开前端领域,目前重心放在研究区块链上面了

我叫朱安邦,阿西河的站长

目前在杭州从事区块链周边的开发工作,机械专业,以前从事平面设计工作。

2014年底脱产在老家自学6个月的前端技术,自学期间几乎从未出过家门,最终找到了满意的前端工作。更多>

于2021年离开前端领域,目前从事区块链方面工作了