JavaScript Date getYear()
Syntax & Examples


Date.getYear() method

The getYear() method of the Date object in JavaScript returns the year (usually 2–3 digits) in the specified date according to local time. It is recommended to use getFullYear() instead.


Syntax of Date.getYear()

The syntax of Date.getYear() method is:

getYear()

This getYear() method of Date returns the year (usually 2–3 digits) in the specified date according to local time. Use getFullYear() instead.

Return Type

Date.getYear() returns value of type Number.



✐ Examples

1 Using getYear() to get the year of a specific date

In JavaScript, we can use the getYear() method to get the year from a Date object. However, it is recommended to use getFullYear() instead.

For example,

  1. We create a new Date object date representing January 15, 2021.
  2. We use the getYear() method to get the year from date.
  3. The year is stored in the variable year.
  4. We log year to the console using console.log() method.

JavaScript Program

const date = new Date('2021-01-15');
const year = date.getYear();
console.log(year);

Output

121

2 Using getYear() with the current date

In JavaScript, we can use the getYear() method to get the current year from the current date. However, it is recommended to use getFullYear() instead.

For example,

  1. We create a new Date object now representing the current date and time.
  2. We use the getYear() method to get the current year from now.
  3. The current year is stored in the variable currentYear.
  4. We log currentYear to the console using console.log() method.

JavaScript Program

const now = new Date();
const currentYear = now.getYear();
console.log(currentYear);

Output

124

3 Using getYear() with a specific date in the past

In JavaScript, we can use the getYear() method to get the year from a specific date in the past. However, it is recommended to use getFullYear() instead.

For example,

  1. We create a new Date object pastDate representing July 4, 1776.
  2. We use the getYear() method to get the year from pastDate.
  3. The year is stored in the variable pastYear.
  4. We log pastYear to the console using console.log() method.

JavaScript Program

const pastDate = new Date('1776-07-04');
const pastYear = pastDate.getYear();
console.log(pastYear);

Output

-124

Summary

In this JavaScript tutorial, we learned about getYear() method of Date: the syntax and few working examples with output and detailed explanation for each example.