Getting time span between two times in C#?

Hunter Mitchell picture Hunter Mitchell · Sep 20, 2012 · Viewed 179.4k times · Source

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;

Answer

Kittoes0124 picture Kittoes0124 · Sep 20, 2012
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".