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
.
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
This should work for you.
string myDate = "05/11/2010";
DateTime date = Convert.ToDateTime(myDate);
int year = date.Year;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With