Getting time span between two times in C#?

C#DatetimeTimespan

C# Problem Overview


I have two textboxes. One for a clock in time and one for clock out. The times will be put in this format:

Hours:Minutes

Lets say I have clocked in at 7:00 AM and clocked out at 2:00 PM.

With my current code, I get a difference of 2 hours, but it should be 7 hours. How would I do that in C#. I was going to convert to the 24 hour, by letting the user select AM or PM, but I got confused.

So, basically, how would I calculate the difference of hours between the two times?

I tried this, but got 2 hours and not 7 when I plugged in the numbers.

DateTime startTime = Convert.ToDateTime(textBox1.Text);
DateTime endtime = Convert.ToDateTime(textBox2.Text);

TimeSpan duration = startTime - endtime;

C# Solutions


Solution 1 - C#

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".

Solution 2 - C#

You could use the TimeSpan constructor which takes a long for Ticks:

 TimeSpan duration = new TimeSpan(endtime.Ticks - startTime.Ticks);

Solution 3 - C#

Two points:

  1. 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.

  2. To find the difference between a start and end time, you need to do endTime - startTime, not the other way around.

Solution 4 - C#

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

Solution 5 - C#

Another way ( longer ) In VB.net [ Say 2300 Start and 0700 Finish next day ]

If tsStart > tsFinish Then

                            ' Take Hours difference and adjust accordingly
                            tsDifference = New TimeSpan((24 - tsStart.Hours) + tsFinish.Hours, 0, 0)

                            ' Add Minutes to Difference
                            tsDifference = tsDifference.Add(New TimeSpan(0, Math.Abs(tsStart.Minutes - tsFinish.Minutes), 0))


                            ' Add Seonds to Difference
                            tsDifference = tsDifference.Add(New TimeSpan(0, 0, Math.Abs(tsStart.Seconds - tsFinish.Seconds)))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHunter MitchellView Question on Stackoverflow
Solution 1 - C#Kittoes0124View Answer on Stackoverflow
Solution 2 - C#Tim LehnerView Answer on Stackoverflow
Solution 3 - C#StriplingWarriorView Answer on Stackoverflow
Solution 4 - C#troll-eView Answer on Stackoverflow
Solution 5 - C#SMAView Answer on Stackoverflow