Given a date in the following string format:
2010-02-02T08:00:00Z
How to get the year with JavaScript?
It's a date, use Javascript's built in Date functions...
var d = new Date('2011-02-02T08:00:00Z');
alert(d.getFullYear());
getFullYear() will return the year in the system's local time zone, so if you want the year in local time, it will be correct, but if you want the year printed in the UTC time given, it may be incorrect on either Jan 1 or Dec 31.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).
Date object is just an overkill, and should be avoided since the ISO-8601 format is not widely supported -yet-, parseInt will work without problems. I would maybe use also dateString.slice(0,4);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.
Date constructor and Date.parse method in ECMAScript 3, are implementation-dependent, the ISO-8601 format was introduced by ECMAScript 5 recently, meaning that you will find implementations that are not able to parse that format. He just wants the first 4 charaacters, I would simply go for dateStr.slice(0,4) ...Date object might be handy is when you live in another timezone than GMT, as the current year number differs around the world round New Year's Eve.parse() until specifically impemented.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.
String.prototype.slice is generally preferred to substr, since it has several bugs across implementations, for example in JScript (IE<=8), it can't handle negative indexes. Both are part of the ECMAScript standard, but substr is non-normative, meaning that a standards compliant implementation is not strictly required to implement substr.slice over substr; every day…