2016-03-08 138 views
-1

我在我的controller.this代码给出了一个异常,当我试图通过DataSet循环。异常是在不同的行当我运行时(例外情况并非发生在确切的行)C# - “字符串未被识别为有效的日期时间”异常

例外是;

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

DateTime arrDate = DateTime.Parse(ds.Tables[0].Rows[i]["CheckInDate"].ToString()); 

我想这太;

DateTime createdDate = DateTime.ParseExact(ds.Tables[0].Rows[i]["CheckInDate"].ToString(), "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture); 

,但还没有成型..

该行的值是2/9/2016 21:20

+0

您传递的CheckInDate的值是多少?我们需要先看看。如果它是'dateimte'字段,则可以在不解析的情况下投射到'DateTime'。 – Lloyd

+0

我的猜测是字符串不是有效的日期时间....?! – Liam

+0

@Lloyd Strings like 2/9/2016 21:20 .. –

回答

4

你只需将它转换为这似乎是DateTime正确的类型,不需要解析:

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

如果它实际上是一个字符串(为什么会这样呢?)使用的M/d/yyyy代替MM/dd/yyyy

DateTime.ParseExact("2/9/2016 21:20", "M/d/yyyy HH:mm", DateTimeFormatInfo.InvariantInfo); 
+0

ds.Tables [0] .Rows [i] [“CheckInDate”]。ToString()将通过2/19/2016 21:20类型的字符串 –

+0

@ThilinaDeSilva:是的,因为ToString返回一个字符串,即使它是一个'DateTime'。你使用过我的代码吗?什么返回'....字段(“CheckInDate”)'? –

-1

下面尝试,

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

我总是使用String.IsNullOrEmpty来验证字符串 – StarterPack

+0

那么这个问题的作者没有添加,因此我认为可能会出现check没有什么,这不是一个有效的理由来评价这个答案。 –

1

ParseExact需要您的字符串正是你解析与模式匹配。

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

您可能需要更改模式以接受单个数字或更改字符串以传递两位数。

0

你需要知道哪种格式的日期被检索,然后用正确的格式

DateTime dt=DateTime.ParseExact(ds.Tables[0].Rows[i]["CheckInDate"].ToString(), "dd/MM/yyyy", CultureInfo.InvariantCulture); 

如果格式不apropiate当前区域性(应用程序的语言和区域)

解析它
// for example language English and region Canada 
DateTime dt=DateTime.Parse(ds.Tables[0].Rows[i]["CheckInDate"].ToString(), new CultureInfo("en-CA")); 

OR

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 

欲了解更多信息,请Custom Date and Time Format Strings

相关问题