The date.getFullYear() is an inbuilt function in JavaScript which is used to fetch the year from a given Date object.
Syntax:
DateObj.getFullYear()
In the above syntax, DateObj is a valid Date object created using Date() constructor from which we want to fetch the year.
Parameter: This function does not take any parameters. It is just used along with a Date Object from which we want to fetch year.
Return Values: It returns the year for the given date.
The following program illustrates the getFullYear() method:
// Here a date has been assigned // while creating Date object var dateobj = new Date( 'October 15, 1996 05:35:32' ); // year from above date object is // being fetched using getFullYear(). var B = dateobj.getFullYear(); // Printing year console.log(B); |
Output:
1996
Errors and Exceptions:
- Program 1: The date of the month must lie between 1 to 31 because a month cannot have more than 31 days. That is why it returns NaN i.e, not a number because date for the month does not exist. Hence, Year will not exist when date of the month is set as 45 or any number which does not lie between 1 to 31.
// Here a date has been assigned
// while creating Date object
var
dateobj =
new
Date(
'October 45, 1996 05:35:32'
);
// year from above date object is
// being fetched using getFullYear().
var
B = dateobj.getFullYear();
// Printing year
console.log(B);
Output:
NaN
- Program 2: If nothing as parameter is given to the Date() constructor, then the getFullYear() function returns current year.
// Creating Date Object
var
dateobj =
new
Date();
// year from above object
// is being fetched using getFullYear().
var
B = dateobj.getFullYear();
// Printing current year
console.log(B);
Output:
2018
Application: It has applications such as getting current year.It is used in websites to validate the age of the user. The following program shows one of the applications of this function. It gives the current year.
// Creating Date Object var dateobj = new Date(); // year from above object // is being fetched using getFullYear() var B = dateobj.getFullYear(); // Printing current year console.log(B); |
Output:
2018
leave a comment
0 Comments