3

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?

ErikE
  • 48,881
  • 23
  • 151
  • 196

2 Answers2

5

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
);
ErikE
  • 48,881
  • 23
  • 151
  • 196
John Sheehan
  • 77,456
  • 30
  • 160
  • 194
  • So if there are a number of possible date formats, I have to TryParseExact each one? – ErikE May 01 '12 at 01:00
  • There's another overload that allows you to specify an array of possible formats and it will try all of them until one works. – John Sheehan May 01 '12 at 01:02
1

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

Matt Searles
  • 2,656
  • 2
  • 16
  • 18