2016-07-18 5 views
2

文字列をDateTimeオブジェクトに変換したい。文字列は「2016年7月18日」の形式で表示されます(日付は変更可能)。明らかに、.Netはこれを有効な日付形式とみなしません。サードパーティライブラリを使用せずにこれを変換する簡単な方法はありますか?DateTimeに変換

+0

あなたは[ 'DateTime.ParseExact()'](https://msdn.microsoft.com/en-us/library/w2sa9yss(V =対をチェックアウトしましたように見えました。 110).aspx)メソッド? – Sidewinder94

+0

動作しませんでした。 –

+0

関連:http://stackoverflow.com/q/2058639/447156 –

答えて

0

それが問題になる可能性があるので、私はString.Replaceを使用していないだろうが、現在の文化の月名を使用して、交換するつもりだ文字列が含まれています。

代わりに、文字列からこの部分を削除することができます:あなたは、現在のカルチャのdatetimeformatが使用されているTryParseExactするIFormatProviderとしてnullを渡すと

string input = "18th Jul 2016"; 
string[] token = input.Split(); // split by space, result is a string[] with three tokens 
token[0] = new string(token[0].TakeWhile(char.IsDigit).ToArray()); 
input = String.Join(" ", token); 
DateTime dt; 
if(DateTime.TryParseExact(input, "dd MMM yyyy", null, DateTimeStyles.None, out dt)) 
{ 
    Console.WriteLine("Date is: " + dt.ToLongDateString()); 
} 

。あなたが英語の名前を強制的に使用したい場合は、CultureInfo.InvariantCultureを渡すことができます。

+0

'CultureInfo.CurrentCulture'よりも優れている方が、' CultureInfo.InvariantCulture'を使う方がいいです。 –

+0

@Ghasan:英語名を強制したいときには良くないが_correct_;)修正をありがとう –

0

回避策:

string dateStr = "18th Jul 2016"; 
dateStr = dateStr.Replace("th", "").Replace("st", "").Replace("rd", "").Replace("nd", ""); 

DateTime date; 
if (DateTime.TryParseExact(dateStr, "dd MMM yyyy", CultureInfo.CurrentCulture, 
                DateTimeStyles.AssumeLocal, out date)) 
{ 

} 
else 
{ 
    // error 
} 
+2

"nd"を忘れないでください – LordWilmore

+2

置き換えアプローチはローカライゼーションの問題を抱えており、いくつかの国では 'st'、' nd'、 'th'または月の名前に 'rd'を付けます。 –

+0

私のコードは、ローカライゼーションの問題が予想されない内部マシン上で実行されるはずで、入力は常にこの形式になりますので、この解決策はうまくいきます。手伝ってくれてありがとう! –

0

そのファッジのビットが、

string result = System.Text.RegularExpressions.Regex.Replace(dt, "[st|th|nd|rd]{2} ", " ", System.Text.RegularExpressions.RegexOptions.IgnoreCase); 
DateTime d = DateTime.Parse(result); 

それは数ヶ月を編集してみてくださいdoesntのように、私はスペースを含ま..私は[0-9] {1,2}から始めとに置き換えるました数は、それはやり過ぎ

0
string dateString = "18th Jul 2016"; 
dateString = Regex.Replace(dateString, @"^(\d{2})(st|nd|rd|th)", "$1"); 
var result = DateTime.ParseExact(dateString, "dd MMM yyyy", CultureInfo.InvariantCulture);