Click here to Skip to main content
15,910,980 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello Sir,

I want to calculate Hours from Time..

Like: StartTime:-9:30

EndTime:-10:30
TotalTime(Hours):-1

I have to calcuate the difference of Two

my code below:-
C#
public void TotalTime()
      {
          try
          {
              DataTable dt = new DataTable();
                  if (dt.Rows.Count > 0)
                  {
                      GridViewRow row = grdDaily.HeaderRow;
                      TextBox txtStartTime = (TextBox)row.FindControl("txtStartTime");
                      TextBox txtEndTime = (TextBox)row.FindControl("txtEndTime");
                      TextBox txtTotalTime = (TextBox)row.FindControl("txtTotalTime");

                      txtTotalTime.Text = Convert.ToDateTime(dt.Compute(" EndTime - StartTime", "EndTime>-1")).ToString("0.00");
                  }
           
          }
          catch
          {
          }
      }
Posted
Updated 20-Dec-11 20:32pm
v2

Use the TimeSpan class.

E.g.
TimeSpan span3 = span1.Subtract(span2);
Console.Write("Difference in hours - " + span3.Hours);


You can convert the text box values to DateTime values by using the DateTime.TryParse method.
 
Share this answer
 
v2
Comments
Prashant Srivastava LKO 21-Dec-11 2:53am    
Sir, Both fields are inside gridview i.e. my problem please guide for this thing
You can also subtract two datetime objects to get a timespan:
DateTime startDate; 
DateTime endDate;
if(DateTime.TryParse(txtStartTime.Text, out startDate) && DateTime.TryParse(txtEndTime.Text, out endDate)){
    TimeSpan duration = endDate - startDate;
    int hours = duration.Hours;
}
 
Share this answer
 
Comments
Prashant Srivastava LKO 21-Dec-11 5:58am    
Both fields are inside gridview i.e. my problem please guide for this thing
Prashant Srivastava LKO 21-Dec-11 5:58am    
I am unable to find control inside gridview
K Herms 21-Dec-11 6:42am    
When do you call TotalTime()? By the way your question is wrong, it is not about calculating time but getting the textboxes.
Prashant Srivastava LKO 22-Dec-11 0:07am    
So Please help me in this way as you told me above
K Herms 22-Dec-11 3:16am    
What is your use case, what do you want to achieve? When do you want to have the duration in hours? Do you want to show it in the gridview as a column or do you want to have the duration in hours when you click a button?

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