I have an array of dates with format like that 1880-01-01T00:00:00.000
. What is the best possible way to get year from this string using javascript?
Asked
Active
Viewed 169 times
-4

ivankoleda
- 340
- 1
- 11
-
3Possible duplicate of [Converting string to date in js](https://stackoverflow.com/questions/5619202/converting-string-to-date-in-js) – Nils Schlüter Jul 28 '17 at 17:31
-
3If you come to Stack Overflow for answers to extremely trivial and easily discovered answers, you're going to have a bad time :( – Jul 28 '17 at 17:32
-
Possible duplicate of [How to parse the year from this date string in JavaScript?](https://stackoverflow.com/questions/4170117/how-to-parse-the-year-from-this-date-string-in-javascript) – Makyen Aug 06 '17 at 23:43
3 Answers
0
var dateString = "1880-01-01T00:00:00.000";
var date = new Date(dateString);
var year = date.getFullYear();
console.log(year); // 1880
// Or simply like:
year = new Date("1880-01-01T00:00:00.000").getFullYear();
console.log(year); // 1880
// Interested what methods can you get from the date Object?
// Hit F12 to open developer console and inspect the object
// console.dir( Date.prototype );
// Or directly from the `date` variable:
// console.dir( date.constructor.prototype );
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date

Roko C. Buljan
- 196,159
- 39
- 305
- 313
-
Also, you can get more than just the year using the [Date object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) (the variable `date` in @Roko's answer) – Robert Dundon Jul 28 '17 at 17:34
0
Why not using the most obvious solution, '1880-01-01T00:00:00.000'.substr(0,4)
?

Stephan
- 2,028
- 16
- 19
-
probably because using `Date` you can get `invalid date` but using `.substr` you can get `"pigs"` - so a false-positive. – Roko C. Buljan Jul 28 '17 at 17:47
-
Testing for `invalid date` needs nearly the same effort as testing the substring to be a valid number. If he knows for sure that his dates have that format an additional test isn't necessary. – Stephan Jul 28 '17 at 17:50
0
You could use String#slice
just for a part copy of the ISO 8601 combined date and time string.
var iso6801 = '1880-01-01T00:00:00.000',
year = iso6801.slice(0, 4);
console.log(year);

Nina Scholz
- 376,160
- 25
- 347
- 392