JavaScript Date getFullYear()
Syntax & Examples
Date.getFullYear() method
The getFullYear() method of the Date object in JavaScript returns the year (4 digits for 4-digit years) of the specified date according to local time.
Syntax of Date.getFullYear()
The syntax of Date.getFullYear() method is:
getFullYear()
This getFullYear() method of Date returns the year (4 digits for 4-digit years) of the specified date according to local time.
Return Type
Date.getFullYear() returns value of type Number
.
✐ Examples
1 Using getFullYear() to get the year of a date
In JavaScript, we can use the getFullYear()
method to get the year from a Date object.
For example,
- We create a new Date object
date
representing January 15, 2021. - We use the
getFullYear()
method to get the year fromdate
. - The year is stored in the variable
year
. - We log
year
to the console usingconsole.log()
method.
JavaScript Program
const date = new Date('2021-01-15');
const year = date.getFullYear();
console.log(year);
Output
2021
2 Using getFullYear() with the current date
In JavaScript, we can use the getFullYear()
method to get the current year from the current date.
For example,
- We create a new Date object
today
representing the current date. - We use the
getFullYear()
method to get the current year fromtoday
. - The current year is stored in the variable
currentYear
. - We log
currentYear
to the console usingconsole.log()
method.
JavaScript Program
const today = new Date();
const currentYear = today.getFullYear();
console.log(currentYear);
Output
2024
3 Using getFullYear() with a specific date in the past
In JavaScript, we can use the getFullYear()
method to get the year from a specific date in the past.
For example,
- We create a new Date object
pastDate
representing July 4, 1776. - We use the
getFullYear()
method to get the year frompastDate
. - The year is stored in the variable
pastYear
. - We log
pastYear
to the console usingconsole.log()
method.
JavaScript Program
const pastDate = new Date('1776-07-04');
const pastYear = pastDate.getFullYear();
console.log(pastYear);
Output
1776
Summary
In this JavaScript tutorial, we learned about getFullYear() method of Date: the syntax and few working examples with output and detailed explanation for each example.