C# 转换;2012年8月“;使用TryParseExact更新时间对象
我试图将格式为“August 2012”的字符串解析为DateTime对象。字符串来自DataTable中的列名C# 转换;2012年8月“;使用TryParseExact更新时间对象,c#,datetime,datetime-format,tryparse,C#,Datetime,Datetime Format,Tryparse,我试图将格式为“August 2012”的字符串解析为DateTime对象。字符串来自DataTable中的列名 string columnName= row[col].ToString(); // "August 2012" 最初我尝试使用DateTime.TryParse() 但它不断返回错误。所以接下来我尝试使用DateTime.TryParseExact,使用正确的cultureformat,如前所述 然而,这也不断返回false。我做错了什么?我是否应该能够将格式为2012年8月的字
string columnName= row[col].ToString(); // "August 2012"
最初我尝试使用DateTime.TryParse()
但它不断返回错误。所以接下来我尝试使用DateTime.TryParseExact,使用正确的cultureformat,如前所述
然而,这也不断返回false。我做错了什么?我是否应该能够将格式为2012年8月的字符串解析为DateTime对象?这将为您提供预期的日期
string columnName= row[col].ToString(); // ==> August 2012
CultureInfo enUS = new CultureInfo("en-US");
DateTime.TryParseExact(columnName, "MMMM yyyy", enUS, DateTimeStyles.None, out columnNameAsDate);
第一:您应该指定确切的区域性。在AFZA文化中,一年中的第八个月被命名为“奥古斯都”,而不是“八月”,这当然会失败
第二:您应该通过正确的格式规范来获取完整的月份名称(MMMM)和年份(yyyy)。我将首先拆分字符串:
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);
}
string columnName= row[col].ToString(); // ==> August 2012
CultureInfo enUS = new CultureInfo("en-US");
DateTime.TryParseExact(columnName, "MMMM yyyy", enUS, DateTimeStyles.None, out columnNameAsDate);
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);
}