没有从数据库获取正确的日期

时间:2016-05-01 04:13:54

标签: c# sql-server

在以下行中未从数据库获取正确的日期。数据库中的实际日期是04/30/2016 09:30:00 PM,但我是01/01/0001 12:00:00 AM。不知道发生了什么。

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

以下是完整的方法:

 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;
    }

从@ManOVision尝试以下建议后进行编辑:

来自文档:&#34;不执行任何转换;因此,检索到的数据必须已经是DateTime对象。&#34; 我之前曾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

3 个答案:

答案 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

答案 1 :(得分: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);

答案 2 :(得分:0)

来自docs:“没有执行任何转换;因此,检索到的数据必须已经是DateTime对象。”

我以前在使用SqlDataReader.Get [type]时遇到过麻烦。尝试将其切换到Convert.ToDateTime(sqlReader.GetValue(1).ToString())或至少检查sqlReader.GetValue(1)从数据库返回的内容。