Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting time span between two times in C#?

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; 
like image 224
Hunter Mitchell Avatar asked Sep 20 '12 21:09

Hunter Mitchell


People also ask

How do I get the time difference between two times in C#?

DateTime date1 = new DateTime(2018, 7, 15, 08, 15, 20); DateTime date2 = new DateTime(2018, 8, 17, 11, 14, 25); Now, get the difference between two dates. TimeSpan ts = date2 - date1; Get the result i.e. the difference in hours.

How do you calculate span time?

The easiest way would be to: TimeSpan time = DateTime. Now - start; Alternatively, you could use a stopwatch which gives more accurate results.

What is TimeSpan C#?

C# TimeSpan struct represents a time interval that is difference between two times measured in number of days, hours, minutes, and seconds. C# TimeSpan is used to compare two C# DateTime objects to find the difference between two dates.


2 Answers

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

like image 166
Kittoes0124 Avatar answered Sep 16 '22 12:09

Kittoes0124


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

 TimeSpan duration = new TimeSpan(endtime.Ticks - startTime.Ticks); 
like image 20
Tim Lehner Avatar answered Sep 18 '22 12:09

Tim Lehner