
So in this case we need to use this overload of the DateTime.Parse method:ĭateTime.Parse(String value, IFormatProvider provider) ĬultureInfo culture = new CultureInfo("es-ES") ĭateTime date = DateTime.Parse(myDate,culture) Īnd this time we get the expected output 15/May/2018. The moral of this story is that when parsing a string as a date we need to know the format used, and we may need to indicate explicitly to the Parse method the Culture (information about the regional configuration) that it needs to use. Run-time exception (line 9): String was not recognized as a valid DateTime. Indeed, instead of the expected DateTime now we got a nasty exception: Now, the code we used a moment ago will not fare so well: Furthermore, take another date like the 15th May: Spanish users will introduce that date as “”. Therefore Spanish citizens would expect the “” string to be converted to December 12th. Notice though that in order to get that output the Parse method has to do some assumptions about the date Format.įor example, some countries – like the United States – use the Month/Day/Year date format, but some other countries – like France, Spain or the U.K – use the Day/Month/Year. Unsurprisingly the code above will print to the console the expected 12/May/2018 value. String was not recognized as a valid DateTime

We will use the Parse method above to convert it to a proper date:Ĭonsole.WriteLine(date.ToString("dd/MMM/yyyy")) The Parse method takes a string parameter and converts it to a DateTime object: Convert a String to DateTime using DateTime.Parse

In this post we will see the most commonly used methods to convert strings into DateTime objects, and some of the issues we can run in. Converting a string to DateTime can be unexpectedly tricky: given that the same date can be represented in a wide myriad of formats, simple tasks – like parsing data from text files – can lead to unexpected results.
