日付/時刻の形式が正確にわかっている場合(すなわち決して変更されず、ユーザーの文化やロケールに依存しない場合)は、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/M/yyyy
に似た日付は、正規表現\d{1,2}\/\d{1,2}\/\d{4}
を使用して見つけることができます。
http://stackoverflow.com/questions/11660423/string-comparison-on-date-format-wont-workの可能性の重複 – MikeKulls
のための有用な基準であります代わりにLINQクエリ構文を使用する人々http://stackoverflow.com/questions/9003697/how-to-i-use-tryparse-in-a-linq-query-of-xml-data –