Click here to Skip to main content
15,891,423 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
guys could you give me some example to this i want to get the numbers of hours between two time like t1=10:00AM and t2=12:00PM therefore t3=2???

thanks a lot =>
Posted
Updated 14-Mar-22 20:39pm

C#
DateTime dFrom;
DateTime dTo;
string sDateFrom = "11:56:00";
string sDateTo = "12:12:00";
if (DateTime.TryParse(sDateFrom, out dFrom) && DateTime.TryParse(sDateTo, out dTo))
{
      TimeSpan TS = dTo - dFrom;
      int hour = TS.Hours;
      int mins = TS.Minutes;
      int secs = TS.Seconds;
      string timeDiff = hour.ToString("00") + ":" + mins.ToString("00") + ":" + secs.ToString("00");
      Response.Write(timeDiff); //output 16 mins in format 00:16:00
}
 
Share this answer
 
v2
Comments
newbie011292 23-Feb-12 0:46am    
how about the AM and PM sir? im using DateTime.Now.ToShortTimeString() or is there a better way to user?or etc thanks for the help=>
newbie011292 23-Feb-12 11:11am    
thanks
Bhaiyasaheb 15002513 30-Dec-20 1:50am    
thank you its work for me
Given,

t1=10:00 AM<br />
t2=12:00 PM


To Calculate difference in hours:

C#
DateTime dtFrom = DateTime.Parse("10:00 AM");
DateTime dtTo = DateTime.Parse("12:00 PM");

int timeDiff = dtFrom.Value.Subtract(dtTo.Value).Hours;


timeDiff is the difference in hours you require
 
Share this answer
 
Comments
newbie011292 23-Feb-12 11:11am    
thanks
Member 13296293 12-Sep-17 0:54am    
its not working..sir..
C#
TimeSpan timeSpan1 = new TimeSpan(10, 0, 0);
TimeSpan timeSpan2 = new TimeSpan(12, 0, 0);
var timeDiff = timeSpan2.Subtract(timeSpan1);
DateTime dt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, timeDiff.Hours, timeDiff.Minutes, timeDiff.Seconds, DateTimeKind.Local);
 
Share this answer
 
v2
private void CalculateDifference(DateTime ontime, DateTime offtime)
       {
           TimeSpan ts = offtime.Subtract(ontime);
           txtHrs.Text = ts.Hours.ToString().Replace("-", "");
           txtMins.Text = ts.Minutes.ToString().Replace("-", "");
       }

       protected void txtclose_ValueChanged(object sender, EventArgs e)
       {
           DateTime ontime = Convert.ToDateTime(txtonn.Text.Trim());
           DateTime offtime = Convert.ToDateTime(txtclose.Text.Trim());
           this.CalculateDifference(offtime, ontime);
       }


//or line 1 =
TimeSpan ts = offtime.Subtract - ontime;
 
Share this answer
 
v2

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