我有一个日期数组,格式类似于1880-01-01T00:00:00.000
。使用javascript从这个字符串中获取年份的最佳方法是什么?
答案 0 :(得分: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
答案 1 :(得分:0)
为什么不使用最明显的解决方案'1880-01-01T00:00:00.000'.substr(0,4)
?
答案 2 :(得分:0)
您只能将String#slice
用于ISO 8601组合日期和时间字符串的部分副本。
var iso6801 = '1880-01-01T00:00:00.000',
year = iso6801.slice(0, 4);
console.log(year);