などの形式で日付を解析するために.Netフレームワークに組み込まれているものはありませんJanuary 11th or February 22nd
。サフィックス文字を削除する必要があり、その後使用できます DateTime.TryParseExact
。
サフィックスst
が ,の日付についてはth
、 を使用string.Replace
してその部分を削除してから を使用できますDateTime.TryParseExact
。お気に入り。
string str = "1st February 2013";
DateTime dtObject;
string replacedStr = str.Substring(0,4)
.Replace("nd","")
.Replace("th","")
.Replace("rd","")
.Replace("st","")
+ str.Substring(4);
if (DateTime.TryParseExact(replacedStr,
"dd MMMMM yyyy",
CultureInfo.InstalledUICulture,
DateTimeStyles.None,
out dtObject))
{
//valid date
}
複数の形式の場合、文字列配列で形式を指定し、後でそれを使用できます。bool
解析が成功したかどうかを示す値を返します。
MSDN の例:
string[] formats= {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt",
"MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss",
"M/d/yyyy hh:mm tt", "M/d/yyyy hh tt",
"M/d/yyyy h:mm", "M/d/yyyy h:mm",
"MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm"};
string[] dateStrings = {"5/1/2009 6:32 PM", "05/01/2009 6:32:05 PM",
"5/1/2009 6:32:00", "05/01/2009 06:32",
"05/01/2009 06:32:00 PM", "05/01/2009 06:32:00"};
DateTime dateValue;
foreach (string dateString in dateStrings)
{
if (DateTime.TryParseExact(dateString, formats,
new CultureInfo("en-US"),
DateTimeStyles.None,
out dateValue))
Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue);
else
Console.WriteLine("Unable to convert '{0}' to a date.", dateString);