当日期字符串附加了星期几时,TryParse 失败:
DateTime d;
string dateString = "Tuesday May 1, 2012 9:00 AM";
return DateTime.TryParse(dateString, out d); // returns false
处理此问题的最佳方法是什么,以便我可以安全地确定它是一个日期,并将其转换为日期?
您需要告诉 TryParseExact 要查找的格式:
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
);
这应该可以解决问题:)
// 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);
参考 http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx