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

黄舟
Release: 2017-11-06 09:56:37
Original
2992 people have browsed it

Definition and usage

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

Syntax

dateObject.getYear()
Copy after login

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>
Copy after login

Output:

117
Copy after login

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>
Copy after login

Output:

I was born in 83
Copy after login

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()
Copy after login

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>
Copy after login

This will produce the following results for 2012:

getYear() : 212
Copy after login

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!

Related labels:
Statement of this Website
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
Latest Issues
What are JavaScript hook functions?
From 1970-01-01 08:00:00
0
0
0
What is JavaScript garbage collection?
From 1970-01-01 08:00:00
0
0
0
c++ calls javascript
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template