Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# ";字符串未被识别为有效的日期时间;例外_C#_Asp.net_Asp.net Mvc - Fatal编程技术网

C# ";字符串未被识别为有效的日期时间;例外

C# ";字符串未被识别为有效的日期时间;例外,c#,asp.net,asp.net-mvc,C#,Asp.net,Asp.net Mvc,我的控制器中有此代码。当我尝试循环遍历数据集时,此代码会出现异常。当我多次运行项目时,会在不同的行上出现此异常。(此异常不会发生在确切的行上) 例外情况是 字符串未被识别为有效的日期时间 我也试过了 DateTime createdDate = DateTime.ParseExact(ds.Tables[0].Rows[i]["CheckInDate"].ToString(), "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture); 但是它还没有起

我的控制器中有此代码。当我尝试循环遍历数据集时,此代码会出现异常。当我多次运行项目时,会在不同的行上出现此异常。(此异常不会发生在确切的行上)

例外情况是

字符串未被识别为有效的日期时间

我也试过了

DateTime createdDate = DateTime.ParseExact(ds.Tables[0].Rows[i]["CheckInDate"].ToString(), "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture);
但是它还没有起作用


行的值为
2/9/2016 21:20

您只需将其转换为正确的类型,即
DateTime
,无需解析:

DateTime arrDate = ds.Tables[0].Rows[i].Field<DateTime>("CheckInDate");
试试下面

If ( ds.Tables[0].Rows[i]["CheckInDate"] != null ) {
// your code goes here...
DateTime arrDate = DateTime.Parse(ds.Tables[0].Rows[i]["CheckInDate"].ToString());
}

ParseExact
要求字符串与解析所依据的模式完全匹配

您的模式有“MM/dd”,需要两位数的月份和天数(“01/29”或“10/02”或“01/02”),但您只传递一位数的月份和天数(“2/9”)


您需要更改模式以接受一位数,或更改字符串以传递两位数。

您需要知道检索日期的格式,然后使用正确的格式对其进行解析

DateTime dt=DateTime.ParseExact(ds.Tables[0].Rows[i]["CheckInDate"].ToString(), "dd/MM/yyyy", CultureInfo.InvariantCulture);
如果此格式不适用于当前区域性(应用程序的语言和区域)


有关更多信息,请查看您要传递的
CheckInDate
的值是多少?我们需要先看看这个。如果它是一个
dateimte
字段,您可以在不进行解析的情况下强制转换为
DateTime
。我猜字符串不是有效的日期时间@Lloyd字符串,如2/9/2016 21:20。首先,我会尝试使用TryParse,并检查哪些字符串失败
DateTime dt=DateTime.Parse(“2/9/2016 21:20”,CultureInfo.InvariantCulture)对我来说工作正常BTWI将始终使用String.IsNullOrEmpty来验证stringsWell。这个问题的作者没有补充这一点。所以我想可能会有空头支票的问题。这不是降低此答案评级的有效原因。ds.Tables[0]。行[i][“CheckInDate”]。ToString()将通过2016年2月19日21:20类型的strings@ThilinaDeSilva:是,因为
ToString
返回字符串,即使它是
DateTime
。你用过我的密码吗?什么返回
…字段(“CheckInDate”)
If ( ds.Tables[0].Rows[i]["CheckInDate"] != null ) {
// your code goes here...
DateTime arrDate = DateTime.Parse(ds.Tables[0].Rows[i]["CheckInDate"].ToString());
}
DateTime dt=DateTime.ParseExact(ds.Tables[0].Rows[i]["CheckInDate"].ToString(), "dd/MM/yyyy", CultureInfo.InvariantCulture);
// for example language English and region Canada
DateTime dt=DateTime.Parse(ds.Tables[0].Rows[i]["CheckInDate"].ToString(), new CultureInfo("en-CA"));
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-CA");
DateTime dt = DateTime.Parse(ds.Tables[0].Rows[i]["CheckInDate"].ToString()); //uses the current Thread's culture