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
0 Comments