I found an example in MSDN for string to datetime conversion. But it doesn’t work, fall into the catch(). Why this code block doesn’t work?
DateTime dateValue;
string dateString = "2/16/2008 12:15:12 PM";
try {
dateValue = DateTime.Parse(dateString);
Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
}
catch (FormatException) {
Console.WriteLine("Unable to convert '{0}'.", dateString);
}
You’re using whatever the current culture’s idea of a date/time format is – and my guess is that you’re in a culture where the day normally comes before the month.
If you know the format, I’d typically use the invariant culture and
TryParseExact– definitely don’t useParseand a catch block; either useTryParseExactorTryParse. In this case:If you don’t know the input format, but you know the culture to use, I’d just use
DateTime.TryParsewith the appropriate culture.