How to get the time duration from subtracting two times

63 views Asked by At

I have userTransact table that contains the (login and logout) time and date , now I used these codes for the duration calculation but the problem is that it subtarct dates also giving me invalid date as follows:
login 2016-12-22 08:28:27.540
logout 2016-12-22 08:28:32.947
duration 1900-01-01 00:00:05.407
How to fix this problem?
The codes for this calculation are in the FormClosing event as:

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

There are 1 answers

6
ProgrammingLlama On
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();  

Be aware that TotalSeconds isn't an integer value.