2012-07-26 7 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

+0

のための有用な基準であります代わりにLINQクエリ構文を使用する人々http://stackoverflow.com/questions/9003697/how-to-i-use-tryparse-in-a-linq-query-of-xml-data –

答えて

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/M/yyyyに似た日付は、正規表現\d{1,2}\/\d{1,2}\/\d{4}を使用して見つけることができます。

+0

+1 0 PRINT "Daniel" –

+0

10 GOTO WHAT '? –

0

もう1つの方法は、stringからDateTimeに日付を変換することです。可能であれば、DateAddedDateTimeとしてください。

ベローは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; 
} 
関連する問題