如何减去两次的持续时间

时间:2016-12-29 17:01:14

标签: c# winforms datetime duration

我有userTransact表,其中包含(登录和注销)时间和日期,现在我使用这些代码进行持续时间计算,但问题是它的subtarct日期也给我无效日期如下:
登录2016-12-22 08:28:27.540
退出2016-12-22 08:28:32.947
持续时间1900-01-01 00:00:05.407
如何解决这个问题?
此计算的代码位于FormClosing事件中:

SqlCommand cmd3 = new SqlCommand("insert into empTransLogin(empLogTransNo,empId,logTimeIn,logTimeOut,duration) VALUES (@logTrans,@id,@login,@logout,@duration)", cn);
cmd3.Parameters.AddWithValue("@logTrans", x);
cmd3.Parameters.AddWithValue("@id", deleteById);
cmd3.Parameters.AddWithValue("@login", loginDateTime);
cmd3.Parameters.AddWithValue("@logout", DateTime.Now);
TimeSpan duration = DateTime.Now - loginDateTime;
cmd3.Parameters.AddWithValue("@duration", duration);
cmd3.ExecuteNonQuery();
SqlCommand cmd2 = new SqlCommand("delete from empLogin where empId=" + deleteById + "", cn);
cmd2.ExecuteNonQuery();
Application.Exit();  

1 个答案:

答案 0 :(得分:2)

SqlCommand cmd3 = new SqlCommand("insert into empTransLogin(empLogTransNo,empId,logTimeIn,logTimeOut,duration) VALUES (@logTrans,@id,@login,@logout,@duration)", cn);
cmd3.Parameters.AddWithValue("@logTrans", x);
cmd3.Parameters.AddWithValue("@id", deleteById);
cmd3.Parameters.AddWithValue("@login", loginDateTime);
cmd3.Parameters.AddWithValue("@logout", DateTime.Now);
TimeSpan duration = DateTime.Now - loginDateTime;
cmd3.Parameters.AddWithValue("@duration", duration.TotalSeconds);
cmd3.ExecuteNonQuery();
SqlCommand cmd2 = new SqlCommand("delete from empLogin where empId=" + deleteById + "", cn);
cmd2.ExecuteNonQuery();
Application.Exit();  

请注意,TotalSeconds不是整数值。