如果您确切知道日期/时间的格式(即它永远不会改变,并且不依赖于用户的文化或区域设置),那么您可以使用DateTime.TryParseExact。
例如:
DateTime result;
if (DateTime.TryParseExact(
str, // The string you want to parse
"dd-MM-yyyy", // The format of the string you want to parse.
CultureInfo.InvariantCulture, // The culture that was used
// to create the date/time notation
DateTimeStyles.None, // Extra flags that control what assumptions
// the parser can make, and where whitespace
// may occur that is ignored.
out result)) // Where the parsed result is stored.
{
// Only when the method returns true did the parsing succeed.
// Therefore it is in an if-statement and at this point
// 'result' contains a valid DateTime.
}
格式字符串可以是完全指定的custom date/time format(如dd-MM-yyyy)或general format specifier(如g)。对于后者,文化对于日期的格式很重要。例如,在荷兰,日期写为 26-07-2012 (dd-MM-yyyy),而在美国,日期写为 7/26/2012 (M/d/yyyy)。
但是,这一切仅在您的字符串 str 仅包含您要解析的日期时才有效。如果您有一个较大的字符串,并且日期周围有各种不需要的字符,那么您必须首先在其中找到日期。这可以使用正则表达式来完成,这本身就是另一个主题。可以在here 找到有关 C# 中的正则表达式 (regex) 的一些一般信息。正则表达式引用是here。例如,可以使用正则表达式 \d{1,2}\/\d{1,2}\/\d{4} 找到类似于 d/M/yyyy 的日期。