2012-08-17 135 views
-2

我一直在網上尋找一個例子,將解決我的問題與字符串轉換爲日期時間。將字符串轉換爲datetime問題

我想將en-us(mm/dd/yyyy)轉換爲荷蘭比利時(dd/mm/yyyy)日期時間。 你能給我舉個例子嗎?

爲了您的信息,我已經嘗試過Convert.ToDateTime,Parse,TryParse,ParseExact等,但都沒有工作。我非常喜歡這個轉換的例子,沒有任何無用的鏈接。


Upate

我得到的錯誤是:字符串未被識別爲有效的DateTime。 我曾嘗試:

---------------- 
string str = "02/20/2012"; 
DateTime dt = Convert.ToDateTime(str); 
--------------------- 
IFormatProvider theCultureInfo = new System.Globalization.CultureInfo("nl-BE", true); 
DateTime theDateTime = DateTime.ParseExact(deliveryDate, "dd/mm/yyyy", theCultureInfo); 
Console.WriteLine(dt); 
---------------------- 
var parsed = DateTime.ParseExact("02/20/2012","dd/mm/yyyy", null); 
--------------- 

dateValue = DateTime.Parse(dateString, new CultureInfo("nl-BE", false)); 

和我不記得他們現在其他一些例子。但所有領先的沒有。

+0

你想要字符串轉換爲字符串嗎? – 2012-08-17 18:22:33

+0

DateTime應該支持CultureInfo。請參閱:http://stackoverflow.com/questions/313781/localization-of-date-time-using-custom-patterns – Brandon 2012-08-17 18:24:44

+2

我向你保證,ParseExact是workng罰款。 – 2012-08-17 18:25:22

回答

7

使用這些方法重載:

,並通過一個CultureInfo.DateTimeFormat對他們說:

string enUsDateString = "12/31/2012"; 
IFormatProvider enUsDateFormat = new CultureInfo("en-US").DateTimeFormat; 

DateTime date = DateTime.Parse(enUsDateString, enUsDateFormat); 

IFormatProvider nlBeDateFormat = new CultureInfo("nl-BE").DateTimeFormat; 
string nlBeDateString = date.ToString(nlBeDateFormat); 

這種意志,然而,也包括時間分量在輸出中。如果你不想那樣,例如:

IFormatProvider nlBeDateFormat = new CultureInfo(…).DateTimeFormat.ShortDatePattern; 
//                ^^^^^^^^^^^^^^^^^