2016-12-29 34 views
0

我有包含(登录和注销)时间和日期的userTransact表,现在我使用这些代码进行持续时间计算,但问题是它使得日期也使我无效日期如下:
登录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

应该怎么看'duration'?当你做'logout-login'时,你会从这里得到'TimeSpan',你可以在几秒钟内获得持续时间,抽动或者你想要的东西 –

+0

请不要使用'AddWithValue'。这可能会造成问题:[最佳实践 - 执行Sql语句](http://stackoverflow.com/documentation/.net/3589/ado-net/14261/best-practices-executing-sql-statements)。 –

+0

@M.Wiśnicki持续时间应该是完整日期,然后是全部时间,这里时间是正确的,但日期不是。如果用户在同一天登录并注销,它应该是同一日期。 –

回答

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不是一个整数值。

+0

在我的代码中的时间是完全确定的问题是与日期期待期间1900-01-01 00:00:00 05.407 –

+0

你是什么类型的数据库中保存持续时间?您是如何获得年份,月份等的价值,因为持续时间不是日期类型? – john

+0

类型是数据库中的日期时间 –

相关问题