2016-12-29 35 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

類型是數據庫中的日期時間 –

相關問題