嘿你怎么能在给定日期做一个字符串比较匹配,DateTime.TryParseExact看起来像是明智的选择,但我不知道如何在下面的方法中构建争论:
public List<Dates> DateEqualToThisDate(string dateentered)
{
List<Dates> date = dates.Where(
n => string.Equals(n.DateAdded,
dateentered,
StringComparison.CurrentCultureIgnoreCase)).ToList();
return hiredate;
}
Run Code Online (Sandbox Code Playgroud)
Dan*_*ker 13
如果您确切地知道日期/时间的格式(即它永远不会改变,并且不依赖于用户的文化或区域设置),那么您可以使用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.
}
Run Code Online (Sandbox Code Playgroud)
格式字符串可以是完全指定的自定义日期/时间格式(例如dd-MM-yyyy),也可以是通用格式说明符(例如g).对于后者,文化对于如何格式化日期很重要.例如,在荷兰,日期写为26-07-2012(dd-MM-yyyy)而在美国,日期写为7/26/2012(M/d/yyyy).
但是,只有当您的字符串str仅包含要解析的日期时,这一切才有效.如果你有一个更大的字符串,在日期周围有各种不需要的字符,那么你必须先在那里找到日期.这可以使用正则表达式来完成,正则表达式本身就是一个完整的其他主题.有关C#中正则表达式(regex)的一些一般信息可以在这里找到.正则表达式引用在这里.例如,d/M/yyyy使用正则表达式可以找到类似的日期\d{1,2}\/\d{1,2}\/\d{4}.