ErikE
ErikE

Reputation: 50271

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?

Upvotes: 3

Views: 1411

Answers (2)

John Sheehan
John Sheehan

Reputation: 78152

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
);

Upvotes: 5

Matt Searles
Matt Searles

Reputation: 2765

This should do the trick :)

        // Parse date and time with custom specifier.
        string dateValue = "Tuesday May 1, 2012 9:00 AM";
        string pattern = "dddd MMMM d, yyyy h:mm tt";

        DateTime parsedDate;

        if (DateTime.TryParseExact(dateValue, pattern, null,
                               DateTimeStyles.None, out parsedDate))
            Console.WriteLine("Converted '{0}' to {1:d}.",
                              dateValue, parsedDate);
        else
            Console.WriteLine("Unable to convert '{0}' to a date and time.",
                              dateValue);

Reference http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

Upvotes: 1

Related Questions