2017-10-13 204 views
3

我正在嘗試將格式爲「2012年8月」的字符串解析爲DateTime對象。該字符串來自DataTable中的列名稱。使用TryParseExact將「2012年8月」轉換爲DateTime對象

string columnName= row[col].ToString(); // "August 2012" 

起初我嘗試使用DateTime.TryParse()...

bool result = DateTime.TryParse(row[col].ToString, out convertedDateTime); 

但它一直返回false。所以下次我試着用DateTime.TryParseExact使用正確的cultureformat描述here ...

CultureInfo enUS = new CultureInfo("af-ZA"); 
DateTime.TryParseExact(row[col].ToString(), "y", enUS, DateTimeStyles.None, out columnNameAsDate) 

然而,這回頭率假也。我究竟做錯了什麼?我不應該能夠將格式爲2012年8月的字符串解析爲DateTime對象嗎?

回答

3

這應該給你預期的日期。

string columnName= row[col].ToString(); // ==> August 2012 
CultureInfo enUS = new CultureInfo("en-US"); 
DateTime.TryParseExact(columnName, "MMMM yyyy", enUS, DateTimeStyles.None, out columnNameAsDate); 

第一:您應該指定確切的文化。在af-ZA文化中,一年的第八個月被命名爲「奧古斯都」而不是「八月」,這當然會失敗。

第二:您應該傳遞正確的格式規範以獲取完整的月份名稱(MMMM)和年份(yyyy)。

0

我會先分割字符串:

DateTime outDate = new DateTime(); 
string[] words = columnName.Split(' '); 
if(words.Length>1){ 
    string month = words[0].Substring(0,3); 
    string year = words[1]; 
    outDate = DateTime.ParseExact(month+' '+year, 
    "MMM yyyy", System.Globalization.CultureInfo.InvariantCulture); 
} 
相關問題