Home >Web Front-end >JS Tutorial >JavaScript method getYear() that returns a two- or four-digit number representing the year

JavaScript method getYear() that returns a two- or four-digit number representing the year

黄舟
黄舟Original
2017-11-06 09:56:372932browse

Definition and usage

getYear() method can return a two- or four-digit number representing the year.

Syntax

dateObject.getYear()

Return value

Returns the year field of the Date object.

Tips and Notes:

Note: The value returned by getYear() is not always a 4-digit number! For years between 1900 and 1999, the getYear() method returns only two digits. For years before 1900 or after 1999, 4 digits are returned!

Note: This method is always used in conjunction with a Date object.

Important: Starting from ECMAScript v3, JavaScript implementations no longer use this method and use the getFullYear() method instead!

Example

Example 1

In this example, we will get the current year and output it:

<script type="text/javascript">

var d = new Date()
document.write(d.getYear())

</script>

Output:

117

Example 2

In this example, we will extract the year from a specific date:

<script type="text/javascript">

var born = new Date("July 21, 1983 01:15:00")
document.write("I was born in " + born.getYear())

</script>

Output:

I was born in 83

The value returned by getYear is the current Subtracts 1900 from the year (in JavaScript 1.2) and returns the year which is either a 2 or 4 digit year, for example if the year is 2026, the returned value is 2026 so before testing this function make sure JavaScript version.

Date.getYear()

Returns the year of the specified date according to universal time.

Example:

<html>
<head>
<title>JavaScript getYear Method</title>
</head>
<body>
<script type="text/javascript">
  var dt = new Date();
  document.write("getYear() : " + dt.getYear() ); 
</script>
</body>
</html>

This will produce the following results for 2012:

getYear() : 212

The above is the detailed content of JavaScript method getYear() that returns a two- or four-digit number representing the year. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn