Click here to Skip to main content
15,896,207 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm Trying to calculate start and end time and save it to total column spend by the user in data base and it is Saving Like
0:0:0 

and following is my code
thanks in advance
C#
mydb db = new mydb();
string st = "";
DateTime dt1 = DateTime.Now;
DateTime dt = DateTime.Now;
protected void Page_Load(object sender, EventArgs e)
{
   if (!IsPostBack)
   {
      st = "insert into tbl_time(time_in) values('" + dt.ToString("hh:mm:ss") + "')";
      db.ExeQuery(st);
   }
}
protected void btn_save_Click(object sender, EventArgs e)
{
   TimeSpan ts = dt1 - dt;
   st = "update tbl_time set time_out='" + dt1.ToString("hh:mm:ss") + "',tot='" + ts + "'";
   int x = db.ExeQuery(st);
   if (x > 0)
   {
      Response.Write("Saved");
   }
   else
   {
      Response.Write("NOt Savd");
   }
}
Posted
Updated 13-Feb-15 21:15pm
v3

Do not concatenate values to your SQL statement, instead use SqlParameter[^]

The other thing is that you initialize the dt1 and dt to the same value and never change them. Perhaps the code should look like
C#
...
protected void Page_Load(object sender, EventArgs e)
{
   if (!IsPostBack)
   {
      st = "insert into tbl_time(time_in) values('" + dt.ToString("hh:mm:ss") + "')";
      db.ExeQuery(st);
      dt1 = DateTime.Now;
   }
}
...

Well, actually with parameters the code should look like
C#
...
protected void Page_Load(object sender, EventArgs e)
{
   if (!IsPostBack)
   {
      st = "insert into tbl_time(time_in) values(@timevalue)";       
      // here goes the code that sets the value of parameter @timevalue 
      db.ExeQuery(st);
      dt1 = DateTime.Now;
   }
}
...
 
Share this answer
 
v2
You can have table having columns Session_Start,Session_End,Total_Time_On_MY_Site.
Insert current time when session starts. Do same on session End. And then calculate Total_Time_On_MY_Site from above two times.
Do you want time spend for guest user??
If yes then when the user session starts get DateTime.Now(); then add to each page Javascript on leave page to know the exact time the user left.. u do the math :)
 
Share this answer
 
Im getting the same result like 0:0:0 in the Timspan i.e ts
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900