How to parse the year from this date string in Jav

2019-04-07 15:40发布

Given a date in the following string format:

2010-02-02T08:00:00Z

How to get the year with JavaScript?

5条回答
Ridiculous、
2楼-- · 2019-04-07 15:53
var year = '2010-02-02T08:00:00Z'.substr(0,4)

...

var year = new Date('2010-02-02T08:00:00Z').getFullYear()
查看更多
霸刀☆藐视天下
3楼-- · 2019-04-07 15:56

It's a date, use Javascript's built in Date functions...

var d = new Date('2011-02-02T08:00:00Z');
alert(d.getFullYear());
查看更多
甜甜的少女心
4楼-- · 2019-04-07 16:01

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.

查看更多
ら.Afraid
5楼-- · 2019-04-07 16:02

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).

查看更多
6楼-- · 2019-04-07 16:04

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.

查看更多
登录 后发表回答