2012-07-26 77 views
5

嘿,你该怎么办给定日期字符串比较匹配,DateTime.TryParseExact似乎是一个明智的选择,但我不知道如何构造arguement在下面的方法:用于字符串比较DateTime.TryParseExact方法

public List<Dates> DateEqualToThisDate(string dateentered) 
{ 
    List<Dates> date = dates.Where(
     n => string.Equals(n.DateAdded, 
          dateentered, 
          StringComparison.CurrentCultureIgnoreCase)).ToList(); 
     return hiredate; 
} 
+0

用于http://stackoverflow.com/questions/11660423/string-comparison-on-date-format-wont-work – MikeKulls 2012-07-26 00:34:57

+0

有用参考可能重复的码人们使用LINQ查询语法来代替http://stackoverflow.com/questions/9003697/how-to-i-use-tryparse-in-a-linq-query-of-xml-data – 2012-07-26 00:43:12

回答

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. 
} 

格式字符串可以是完全指明的custom date/time format(如dd-MM-yyyy)或general format specifier(如g)。对于后者,文化至关重要的是如何格式化日期。例如,在荷兰,日期为26-07-2012dd-MM-yyyy),而在美国的日期则写为7/26/2012M/d/yyyy)。

但是,这一切仅适用于字符串str仅包含您想要解析的日期。如果你在日期附近有更多的字符串和各种不需要的字符,那么你必须先找到那里的日期。这可以使用正则表达式来完成,这是一个完整的其他主题。有关C#中正则表达式(正则表达式)的一些常规信息可以在here找到。正则表达式引用是here。例如,可以使用正则表达式\d{1,2}\/\d{1,2}\/\d{4}找到类似于d/M/yyyy的日期。

+0

+1 0 PRINT“Daniel” – 2012-07-26 00:45:00

+0

10 GOTO什么? – 2012-07-26 00:51:44

0

另一种方法是将日期从string转换为DateTime。如果有可能我会保留DateAdded作为DateTime

娄的是,在运行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; 
}