2014-12-19 68 views
-2

首先我知道其他人發佈了關於此錯誤的消息,但我相信我的問題與其他人不同。我有一個方法,我用來將字符串轉換爲日期時間,我試圖使用DateTime.TryParse方法,但我只使用DateTime.TryParse方法時得到上述錯誤,即使兩個結果完全相同。我很困惑爲什麼會發生這種情況。錯誤:SqlDateTime溢出。必須介於1/1/1753 12:00:00 AM和12/31/9999 11:59:59 PM

My method: 

public static DateTime parseDateTime(string data) 
    { 
     try 
     { 
      return Convert.ToDateTime(data.Replace('"', ' ').Trim()); 
     } 
     catch (FormatException format) 
     { 
      Console.WriteLine(format.Message); 
      Console.WriteLine(data); 
     } 
     catch (OverflowException overflow) 
     { 
      Console.WriteLine(overflow.Message); 
      Console.WriteLine(data); 
     } 

     return DateTime.MaxValue; 
    } 

返回: {2014年11月26日上午12時00分00秒}

My new method: 

DateTime date = new DateTime(); 
using (DailyAmexDataTableAdapter amexAdapter = new DailyAmexDataTableAdapter()) 
{ 
DateTime.TryParse(lineArray[0], out date); 
amexAdapter.Insert(symbol, open, high, low, close, volume, adjClose, date); // error here 
} 

返回: {2014年12月26日上午12時00分00秒}

+2

我在這裏看不到'SqlDateTime'。 – 2014-12-19 10:57:07

+0

使用'DateTime.Parse'時,您不能在標題中出現異常。可能你沒有顯示所有的代碼。 – 2014-12-19 10:58:02

+0

對不起。我忘記了包含拋出異常的行。非常重要我知道@PatrickHofman – user3610374 2014-12-19 10:59:02

回答

1

您正在使用

DateTime.TryParse(lineArray[0], out date); 

lineArray[0]未被識別爲有效日期時,DateTime.TryParse將返回false並將date設置爲DateTime.MinValue。對於sql datedatetime列,這不是有效值。

您正在「初始化」date變量(DateTime date = new DateTime();)無關緊要的事實:tryParse忽略該值並指定一個新值。您可以刪除=new DateTime()

如果它有效,那麼new DateTime()仍然會以DateTime.MinValue結尾。

因此,您需要測試TryParse的結果,如果它是假的,則執行其他操作。

相關問題