Search code examples
c#datetimedayofweektryparse

Recognize DateTime String as valid when containing day names in C#


When a date string has the day of the week attached to it, TryParse fails:

DateTime d;
string dateString = "Tuesday May 1, 2012 9:00 AM";
return DateTime.TryParse(dateString, out d); // returns false

What is the best way to deal with this so that I can safely determine it IS a date, and furthermore convert it to such?


Solution

  • You need to tell TryParseExact what format to look for:

    DateTime d;
    string dateString = "Tuesday May 1, 2012 9:00 AM";
    return DateTime.TryParseExact(
       dateString,
       "dddd MMMM d, yyyy h:mm tt",
       System.Globalization.CultureInfo.CurrentCulture,
       System.Globalization.DateTimeStyles.None,
       out d
    );