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;
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.
The easiest way would be to: TimeSpan time = DateTime. Now - start; Alternatively, you could use a stopwatch which gives more accurate results.
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.
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".
You could use the TimeSpan constructor which takes a long for Ticks:
TimeSpan duration = new TimeSpan(endtime.Ticks - startTime.Ticks);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With