Getting time span between two times in C#?
You could use the TimeSpan constructor which takes a long for Ticks:
TimeSpan duration = new TimeSpan(endtime.Ticks - startTime.Ticks);
string startTime = "7:00 AM";
string endTime = "2:00 PM";
TimeSpan duration = DateTime.Parse(endTime).Subtract(DateTime.Parse(startTime));
Console.WriteLine(duration);
Console.ReadKey();
Will output: 07:00:00.
It also works if the user input military time:
string startTime = "7:00";
string endTime = "14:00";
TimeSpan duration = DateTime.Parse(endTime).Subtract(DateTime.Parse(startTime));
Console.WriteLine(duration);
Console.ReadKey();
Outputs: 07:00:00.
To change the format: duration.ToString(@"hh\:mm")
More info at: http://msdn.microsoft.com/en-us/library/ee372287.aspx
Addendum:
Over the years it has somewhat bothered me that this is the most popular answer I have ever given; the original answer never actually explained why the OP's code didn't work despite the fact that it is perfectly valid. The only reason it gets so many votes is because the post comes up on Google when people search for a combination of the terms "C#", "timespan", and "between".
If i rotate trough sorted list of times (like schedule list) at some point i need to get interval between last and first times , and so far i come to this solution:
TimeSpan t1 = TimeSpan.Parse("23:00");
TimeSpan t2 = TimeSpan.Parse("3:10");
double _24h = (new TimeSpan(24, 0, 0)).TotalMilliseconds;
double diff = t2.TotalMilliseconds - t1.TotalMilliseconds;
if (diff < 0) diff += _24h;
Console.WriteLine(TimeSpan.FromMilliseconds(diff)); // output: 04:10:00
Two points:
Check your inputs. I can't imagine a situation where you'd get 2 hours by subtracting the time values you're talking about. If I do this:
DateTime startTime = Convert.ToDateTime("7:00 AM"); DateTime endtime = Convert.ToDateTime("2:00 PM"); TimeSpan duration = startTime - endtime;
... I get
-07:00:00
as the result. And even if I forget to provide the AM/PM value:DateTime startTime = Convert.ToDateTime("7:00"); DateTime endtime = Convert.ToDateTime("2:00"); TimeSpan duration = startTime - endtime;
... I get
05:00:00
. So either your inputs don't contain the values you have listed or you are in a machine environment where they are begin parsed in an unexpected way. Or you're not actually getting the results you are reporting.To find the difference between a start and end time, you need to do
endTime - startTime
, not the other way around.