2016-12-05 50 views
1

我嘗試將英語日期轉換爲德語,但我的格式不好。轉換英語日期與解析確切

Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); 
DateTime currentCultureDate = DateTime.Now; 
string format = "dd.MM.yyyy HH:mm:ss"; 

Console.WriteLine("Format: " + format); 
Console.WriteLine("Original Date: " + currentCultureDate); 

DateTime convertedDate = DateTime.ParseExact(currentCultureDate.ToString(), format, new CultureInfo("de-DE")); 

Console.WriteLine("Converted Date: " + convertedDate); 

出現FormatException .....

+2

你正在使用'ParseExact',在你的情況下需要格式爲「dd.MM.yyyy HH:mm:ss」',但是你在'currentCultureDate.ToString()'上使用它,它是不是那種格式,因此是'FormatException'。 – Equalsk

+0

但我用toString()轉換它,所以它沒有日期時間和正確的格式 – mty

+0

不正確。打印'currentCultureDate.ToString()'並查看格式。它由'/'分隔。你用'.'指定一個格式,因此錯誤... – Equalsk

回答

2

DateTime.ParseExact被用於從string創建DateTime。您可以通過DateTimeFormatCultureInfo將用於將該字符串轉換爲DateTime

其轉換爲string在另一個CultureInfo的方法,說de-DE。因此,你可以使用DateTime.ToString

string germanFormat = DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss", new CultureInfo("de-DE")); 
1

你沒有做你說什麼:你的代碼實際上是嘗試解析日在德國格式:

// This is German format 
string format = "dd.MM.yyyy HH:mm:ss"; 

// This takes a date and parses it using the ABOVE FORMAT - which is German 
DateTime convertedDate = DateTime.ParseExact(currentCultureDate.ToString(), format, new CultureInfo("de-DE")); 

如果你已經有了一個DateTime你想輸出在德國格式,你不需要ParseExact,但ToString

string german = DateTime.Now.ToString(format, new CultureInfo("de-DE")); 

A DateTime本身沒有附加任何文化格式。這只是一個日期和時間。只有當你輸出 a DateTime,它不知何故需要轉換成一個字符串,這樣做,文化信息是必需的。所以經驗法則是:

  1. 如果你得到一個表示日期和時間值的字符串,你需要解析它變成一個DateTime,或者使用一個固定的格式和ParseExact或依靠框架,將源文化信息傳遞給ParseTryParse
  2. 如果你有一個DateTime並希望輸出它,你需要使用ToString它,提供一個固定格式字符串和文化信息格式化,或使用ToString只對當前線程的文化。