javascript
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?
Similar Posts
- Get current year using Javascript Date getFullYear() method
- Get the day name from given date in Javascript
- Get month name from a date using javascript
- Check if given value is an array in Javascript
- Remove items starting from last untill given condition is false Lodash
- Remove items begin from start until given condition is false Lodash
- add sum of numbers of given numbers