如果您确切地知道日期/时间的格式(即,它永远不会更改,并且不取决于用户的文化或语言环境),那么您可以使用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
仅包含您想要解析的日期。如果你在日期附近有更多的字符串和各种不需要的字符,那么你必须先找到那里的日期。这可以使用正则表达式来完成,这是一个完整的其他主题。有关C#中正则表达式(正则表达式)的一些常规信息可以在here找到。正则表达式引用是here。例如,可以使用正则表达式\d{1,2}\/\d{1,2}\/\d{4}
找到类似于d/M/yyyy
的日期。
用于http://stackoverflow.com/questions/11660423/string-comparison-on-date-format-wont-work – MikeKulls 2012-07-26 00:34:57
有用参考可能重复的码人们使用LINQ查询语法来代替http://stackoverflow.com/questions/9003697/how-to-i-use-tryparse-in-a-linq-query-of-xml-data – 2012-07-26 00:43:12