Reputation: 235
Given a date in the following string format:
2010-02-02T08:00:00Z
How to get the year with JavaScript?
Upvotes: 22
Views: 54106
Reputation: 3399
It's a date, use Javascript's built in Date functions...
var d = new Date('2011-02-02T08:00:00Z');
alert(d.getFullYear());
Upvotes: 35
Reputation: 7960
I would argue the proper way is
var year = (new Date('2010-02-02T08:00:00Z')).getFullYear();
or
var date = new Date('2010-02-02T08:00:00Z');
var year = date.getFullYear();
since it allows you to do other date manipulation later if you need to and will also continue to work if the date format ever changes.
UPDATED: Jason Benson pointed out that Date will parse it for you. So I removed the extraneous Date.parse calls.
Upvotes: 10
Reputation: 29166
You can simply use -
var dateString = "2010-02-02T08:00:00Z";
var year = dateString.substr(0,4);
if the year always remain at the front positions of the year string.
Upvotes: 3
Reputation: 4110
var year = '2010-02-02T08:00:00Z'.substr(0,4)
...
var year = new Date('2010-02-02T08:00:00Z').getFullYear()
Upvotes: 5
Reputation: 700382
You can simply parse the string:
var year = parseInt(dateString);
The parsing will end at the dash, as that can't be a part of an integer (except as the first character).
Upvotes: 12