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.

5 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 
0

This should work for you.

string myDate = "05/11/2010"; DateTime date = Convert.ToDateTime(myDate); int year = date.Year; 
3

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.

you could also used Regex to get the year in the string "05/11/2010"

public string getYear(string str) { return (string)Regex.Match(str, @"\d{4}").Value; } var result = getYear("05/11/2010"); 2010 
2

Variant of dtb that I use:

string Year = DateTime.Parse(DateTime.Now.ToString()).Year.ToString(); 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.