Alex Rivera | Logout

Parsing a date string to get the year

Asked 2012-02-12T04:30:38.263
15

I have a string variable that stores a date like "05/11/2010".

How can I parse the string to get only the year?

So I will have another year variable like year = 2010.

Edit
Report

2 Answers

27

You can use the DateTime.Parse Method to parse the string to a DateTime value which has a Year Property:

var result = DateTime.Parse("05/11/2010").Year;
// result == 2010

Depending on the culture settings of the operating system, you may need to provide a CultureInfo:

var result = DateTime.Parse("05/11/2010", new CultureInfo("en-US")).Year;
// result == 2010
answered 2012-02-12T04:31:45.070
4

If the date string format is fixed (dd/MM/yyyy), I would like to recommend you using DateTime.ParseExact Method.

The code:

const string dateString = "12/02/2012";
CultureInfo provider = CultureInfo.InvariantCulture;
// Use the invariant culture for the provider parameter,
// because of custom format pattern.
DateTime dateTime = DateTime.ParseExact(dateString, "dd/MM/yyyy", provider);
Console.WriteLine(dateTime);

Also I think it might be a little bit faster than DateTime.Parse Method, because the Parse method tries parsing several representations of date-time string.

answered 2012-02-12T16:40:54.330

Your Answer