[英]DateTime.TryParseExact method for string comparison
你怎么能在给定的日期做一个字符串比较匹配, DateTime.TryParseExact
似乎是明智的选择,但我不知道如何在下面的方法中构建争论:
public List<Dates> DateEqualToThisDate(string dateentered)
{
List<Dates> date = dates.Where(
n => string.Equals(n.DateAdded,
dateentered,
StringComparison.CurrentCultureIgnoreCase)).ToList();
return hiredate;
}
如果您确切地知道日期/时间的格式(即它永远不会更改,并且不依赖于用户的文化或区域设置),那么您可以使用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.
}
格式字符串可以是完全指定的自定义日期/时间格式 (例如dd-MM-yyyy
),也可以是通用格式说明符 (例如g
)。 对于后者,文化对于如何格式化日期很重要。 例如,在荷兰,日期写为26-07-2012
( dd-MM-yyyy
),而在美国,日期写为7/26/2012
( M/d/yyyy
)。
但是,只有在字符串str
仅包含要解析的日期时,这一切才有效。 如果你有一个更大的字符串,在日期周围有各种不需要的字符,那么你必须先在那里找到日期。 这可以使用正则表达式来完成,正则表达式本身就是一个完整的其他主题。 有关C#中正则表达式(regex)的一些一般信息可以在这里找到。 正则表达式引用在这里 。 例如,可以使用正则表达式\\d{1,2}\\/\\d{1,2}\\/\\d{4}
找到类似于d/M/yyyy
的日期。
另一种方法是将日期从string
转换为DateTime
。 如果有可能我会将DateAdded
保留为DateTime
。
Bellow是一个在LINQPad中运行的代码
public class Dates
{
public string DateAdded { get; set; }
}
List<Dates> dates = new List<Dates> {new Dates {DateAdded = "7/24/2012"}, new Dates {DateAdded = "7/25/2012"}};
void Main()
{
DateEqualToThisDate("7/25/2012").Dump();
}
public List<Dates> DateEqualToThisDate(string anything)
{
var dateToCompare = DateTime.Parse(anything);
List<Dates> hireDates = dates.Where(n => DateTime.Parse(n.DateAdded) == dateToCompare).ToList();
return hireDates;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.