Search code snippets, questions, articles...

Get year from given date using Javascript

To extract a year from a date using javascript, you can use the below code.
const date = "2018-04-05";
const date_obj = new Date(date);
const year = date_obj.getFullYear();
// -> 2018

// OR The above code can be written in single line
new Date("2018-04-05").getFullYear()
// -> 2018

Here we are given a date "2018-04-05" and we want to get a year from this date string. To do that, first, we create a date object by passing this date string into the new Date("2018-04-05") function. Then we can get the year using the .getFullYear() method of this javascript date object.

Live Demo

Was this helpful?
Programming Feeds
Learn something new everyday on Devsheet