Pierce Reed
Pierce Reed

Reputation: 235

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

Given a date in the following string format:

2010-02-02T08:00:00Z

How to get the year with JavaScript?

Upvotes: 22

Views: 54106

Answers (5)

Jason Benson
Jason Benson

Reputation: 3399

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

var d = new Date('2011-02-02T08:00:00Z');
alert(d.getFullYear());

Upvotes: 35

Rob Van Dam
Rob Van Dam

Reputation: 7960

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.

Upvotes: 10

MD Sayem Ahmed
MD Sayem Ahmed

Reputation: 29166

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.

Upvotes: 3

alxndr
alxndr

Reputation: 4110

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

...

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

Upvotes: 5

Guffa
Guffa

Reputation: 700382

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

Upvotes: 12

Related Questions