2014-11-06 43 views
0

我有来自RSS提要的值Thu, 06 Nov 2014 10:47:21 GMT。我想将此字符串保存到MS SQL数据库中的DateTime字段。但是,我得到一个错误将字符串从RSS提要转换为数据库的DateTime

“字符串未被识别为有效的DateTime”

DateTime date = Convert.ToDateTime(a.PubDate); 
string dateString = a.PubDate; 

DateTime convertedDate = DateTime.ParseExact(dateString, "ddd dd MMM yyyy hh:mm:ss ttt", System.Globalization.CultureInfo.InvariantCulture); 

db.Entry(a).State = System.Data.Entity.EntityState.Modified; 
db.SaveChanges(); 

回答

2

看起来你忘了使用,误用ttt格式说明即使存在。只有ttt说明符,它们用于AM/PM指示符。

string s = "Thu, 06 Nov 2014 10:47:21 GMT"; 
DateTime dt; 
if(DateTime.TryParseExact(s, "ddd, dd MMM yyyy hh:mm:ss 'GMT'", 
          CultureInfo.InvariantCulture, 
          DateTimeStyles.None, out dt)) 
{ 
    Console.WriteLine(dt); 
} 

您需要使用GMT部分为文字字符串分隔符,因为时区的缩写名称不规范。例如; CST可以是中央标准时间或中国标准时间或古巴标准时间。