Вопрос

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?

Это было полезно?

Решение

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

Другие советы

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

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top