Reputation: 1397
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);
}
Upvotes: 1
Views: 4456
Reputation: 72616
Try using ParseExact
passing the appropriate format provider as in this example :
string dateString = "2/16/2008 12:15:12 PM";
string format = "M/dd/yyyy hh:mm:ss tt ";
DateTime dateTime = DateTime.ParseExact(dateString, format,
CultureInfo.InvariantCulture);
Upvotes: 1
Reputation: 1499770
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 use Parse
and a catch block; either use TryParseExact
or TryParse
. In this case:
if (DateTime.TryParseExact(dateString, "M/d/yyyy hh:mm:ss tt",
CultureInfo.InvariantCulture, 0, out dateValue))
{
Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
}
else
{
Console.WriteLine("Unable to convert '{0}'.", dateString);
}
If you don't know the input format, but you know the culture to use, I'd just use DateTime.TryParse
with the appropriate culture.
Upvotes: 5