开发者

How to parse the year from this date string in JavaScript?

Given a date in the followin开发者_如何学Cg 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());


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


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.


var year = '2010-02-02T08:00:00Z'.substr(0,4)

...

var year = new Date('2010-02-02T08:00:00Z').getFullYear()


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜