C# String was not recognized as a valid DateTime

Sometimes while testing someones code, I am getting such exception. Last thing what I want to do is to is fix it 🙂
For example:

// ...
var p = new List<Person>()
{
    new Person() { FirstName="John", LastName="Koenig",
	StartDate = DateTime.Parse("10/17/1975"), Rating=6 },
// ...

This date format, looks like US one, would not work if your current Culture is, say, Canadian.
Just override system setting by adding following line before the code. (If you have different time
format, adjust CultureInfo setting accordingly of course)

// ...
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
// ...

Leave a Reply

Your email address will not be published. Required fields are marked *