Parsing a date string to get a year

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

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

So, I will have a variable of the year, for example year = 2010 .

+7
source share
5 answers

You can use the DateTime.Parse method to parse a string on a DateTime that has a Year Property :

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

Depending on your operating system culture settings, you may need CultureInfo :

 var result = DateTime.Parse("05/11/2010", new CultureInfo("en-US")).Year; // result == 2010 
+19
source

This should work for you.

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

If the date string format is fixed (dd / MM / yyyy), I would recommend that you use the 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 this might be a little faster than the DateTime.Parse Method , because the Parse method is trying to parse multiple date-time representations of a string.

+4
source

you can also use 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
source

The dtb option I'm using is:

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

All Articles