为什么我得到String未被识别为有效的DateTime错误?

时间:2014-07-24 12:12:29

标签: c# datetime

尝试解析s我得到了异常

  

" String未被识别为有效的DateTime"

string s = @"07/24/2014 14:46:47";
DateTime dt = DateTime.Parse(s);

3 个答案:

答案 0 :(得分:3)

System.Globalization.CultureInfo provider =
   System.Globalization.CultureInfo.InvariantCulture;
string dateTimeString = @"07/24/2014 14:46:47";
string dateTimeFormat = @"MM/dd/yyyy HH:mm:ss";
var dateTime = DateTime.ParseExact(dateTimeString, dateTimeFormat, provider);

有用的链接:

答案 1 :(得分:2)

DateTime myDate = DateTime.ParseExact("7/24/2014 14:46:47", 
  "MM/dd/yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);

答案 2 :(得分:0)

正如Sayse和Sriram Sakthivel所说,你需要传递字符串所在的格式

DateTime.ParseExact(s, "MM-dd-yyyy HH:mm:ss", CultureInfo.InvariantCulture);