2016-05-01 46 views
1

在以下幾行中未從數據庫獲取正確的日期。數據庫中的實際日期是04/30/2016 09:30:00 PM,但我將它作爲01/01/0001 12:00:00 AM獲取。不知道發生了什麼事。未從數據庫獲取正確的日期

DateTime fromDb = sqlReader.GetDateTime(1); 
DateTime toDb = sqlReader.GetDateTime(2); 

以下是完整的方法:

從文檔:試圖從@ManOVision以下的建議後

private bool IsRoomAlreadyTaken(String room, DateTime fromUser, DateTime toUser) 
    { 
     bool roomAlreadyTaken = false; 
     using (SqlConnection sqlConnection = new SqlConnection(connectionString)) 
     { 
      SqlCommand sqlCmd = new SqlCommand("SELECT Id, convert(varchar(30), DateFrom, 131), convert(varchar(30), DateTo, 131) FROM Access_Privilege where RoomId = @RoomId", sqlConnection); 
      sqlCmd.Parameters.AddWithValue("@RoomId", room); 
      sqlConnection.Open(); 
      SqlDataReader sqlReader = sqlCmd.ExecuteReader(); 
      while (sqlReader.Read()) 
      { 
       DateTime fromDb = sqlReader.GetDateTime(1); //On this line 
       DateTime toDb = sqlReader.GetDateTime(2); //On this line 

       if (DateTime.Compare(fromUser, fromDb) == 0 && TimeSpan.Compare(fromUser.TimeOfDay, fromDb.TimeOfDay) > 0 && TimeSpan.Compare(toUser.TimeOfDay, toDb.TimeOfDay) <0) 
       { 
        roomAlreadyTaken = true; 
       } 
      } 
      sqlReader.Close(); 
     } 
     return roomAlreadyTaken; 
    } 

編輯「不會進行任何轉換,因此,檢索的數據必須已經是DateTime對象。「 我以前在SqlDataReader.Get[type]之前遇到過麻煩。嘗試將其切換到Convert.ToDateTime(sqlReader.GetValue(1).ToString())或至少檢查從數據庫返回的sqlReader.GetValue(1)

結果,與改變的下列行:

MessageBox.Show("sqlReader.GetValue(1)-->" + sqlReader.GetValue(1)); 
MessageBox.Show("sqlReader.GetValue(2)-->" + sqlReader.GetValue(2)); 
DateTime fromDb = Convert.ToDateTime(sqlReader.GetValue(1).ToString()); 
DateTime toDb = Convert.ToDateTime(sqlReader.GetDateTime(2).ToString()); 

sqlReader.GetValue(1)返回23/07/1437 9:30:12:000 PMsqlReader.GetValue(2)返回23/07/1437 10:30:12:483 PM。隨着GetValue(),時間似乎已經正確返回,但不知何故日期仍然搞砸了。這個實驗證明從DB返回的記錄是正確的。但日期值在轉換中仍然丟失。

在程序的進一步執行,Convert.ToDateTime(sqlReader.GetValue(1).ToString())引發以下錯誤:

String was not recognized as a valid DateTime. 



at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles) 
    at System.Convert.ToDateTime(String value) 
    at SGFinalProjectRoomAllocationSystem.ManageAccessForm.IsRoomAlreadyTaken(String room, DateTime fromUser, DateTime toUser) in c:\Projects\SGFinalProjectRoomAllocationSystem\SGFinalProjectRoomAllocationSystem\ManageAccessForm.cs:line 222 
    at SGFinalProjectRoomAllocationSystem.ManageAccessForm.ValidatePrivilegs(String emp, String room, DateTime from, DateTime to) in c:\Projects\SGFinalProjectRoomAllocationSystem\SGFinalProjectRoomAllocationSystem\ManageAccessForm.cs:line 246 
    at SGFinalProjectRoomAllocationSystem.ManageAccessForm.grntAccssBtn_Click(Object sender, EventArgs e) in c:\Projects\SGFinalProjectRoomAllocationSystem\SGFinalProjectRoomAllocationSystem\ManageAccessForm.cs:line 283 
    at System.Windows.Forms.Control.OnClick(EventArgs e) 
    at System.Windows.Forms.Button.OnClick(EventArgs e) 
    at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent) 
    at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks) 
    at System.Windows.Forms.Control.WndProc(Message& m) 
    at System.Windows.Forms.ButtonBase.WndProc(Message& m) 
    at System.Windows.Forms.Button.WndProc(Message& m) 
    at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) 
    at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) 
    at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) 
    at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg) 
    at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData) 
    at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) 
    at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) 
    at System.Windows.Forms.Application.Run(Form mainForm) 
    at SGFinalProjectRoomAllocationSystem.Program.Main() in c:\Projects\SGFinalProjectRoomAllocationSystem\SGFinalProjectRoomAllocationSystem\Program.cs:line 19 
+0

表中是否有多個結果與您的查詢匹配?您正在使用while循環,因此最後一行將設置您的roomAlreadyTaken變量。 – ManOVision

+1

如果數據庫值是空字符串,那麼將會發生1/1/0001日期,因爲您要轉換爲varchar,然後讓C#將其轉換回DateTime。我的猜測是它正在閱讀的條目是空字符串或空字符串。 – ManOVision

+4

從Sql中刪除'convert'。轉換爲字符串,然後返回到datetime沒有任何意義。 Sql服務器的日期時間直接映射到.Net日期時間。 –

回答

0

docs:「不會進行任何轉換;因此,檢索到的數據必須已經是DateTime對象」。

我以前在使用SqlDataReader.Get [type]之前遇到過麻煩。嘗試將其切換到Convert.ToDateTime(sqlReader.GetValue(1).ToString())或至少檢查從數據庫返回的sqlReader.GetValue(1)

+0

我已經更新了主要帖子和您的建議的結果。請檢查。 @ManOVision –

+1

現在您確定數據庫中的數據是如何返回的,您可以使用正確的轉換方法。文化信息需要通過。以MM/dd/yyyy格式(從更新後的問題中可以看出),轉換將失敗。 – ManOVision

+0

不知道你如何傳遞文化信息。你能建議嗎? –

1

嘗試DateTime.Parse方法。 MSDN

DateTime fromDb = DateTime.Parse(sqlReader[1].ToString()); DateTime toDb = DateTime.Parse(sqlReader[2].ToString());

或者嘗試DateTime.TryParse方法。 MSDN

DateTime fromDb;

if(DateTime.TryParse(sqlReader[1].ToString(), out fromDb)) //Conversion Successful. fromDb is set else //Conversion Unsuccessful

+0

此更改也提供了與MapOVision頂層建議完全相同的結果。日期還是搞砸了。正確的時間。和格式異常。請參閱上面的帖子瞭解這些結果。感謝你的幫助! –

+1

我編輯了我的答案並添加了第二種方法。嘗試一下。它不會給出錯誤。 你可以發佈'sqlReader [1] .ToString()'的輸出。即使您的數據庫列不是'datetime'類型,格式爲2016/4/30 09:30:00的字符串應該被解析爲'DateTime'。 – katu

+0

感謝您的幫助。我已經找到了解決方案併發布爲答案。請檢查。 –

1

轉換方法對造成問題的原因。從查詢中刪除它們解決了它。

代碼的問題:

SqlCommand sqlCmd = new SqlCommand("SELECT Id, convert(varchar(30), DateFrom, 131), convert(varchar(30), DateTo, 131) FROM Access_Privilege where RoomId = @RoomId", sqlConnection); 

工作代碼。

SqlCommand sqlCmd = new SqlCommand("SELECT Id, DateFrom, DateTo FROM Access_Privilege where RoomId = @RoomId", sqlConnection); 
相關問題