Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing a date string to get the year

Tags:

date

c#

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.

like image 232
user1204195 Avatar asked Feb 12 '12 04:02

user1204195


3 Answers

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
like image 155
dtb Avatar answered Nov 07 '22 23:11

dtb


This should work for you.

string myDate = "05/11/2010"; 
DateTime date = Convert.ToDateTime(myDate);
int year = date.Year;
like image 40
Josh Mein Avatar answered Nov 07 '22 23:11

Josh Mein


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.

like image 4
Sergey Vyacheslavovich Brunov Avatar answered Nov 07 '22 22:11

Sergey Vyacheslavovich Brunov