Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting time difference between two values

Tags:

c#

.net

datetime

In my application I have 4 TextBoxes, and 2 TextBoxes to enter the start-time, and 2 TextBoxes to enter end-time.

The user will always enter a completed time, so the input will always be 11:30, 12:45, and so on.

How can I get the difference in hours and minutes between start and endtime?

like image 262
PandaNL Avatar asked May 08 '12 13:05

PandaNL


People also ask

How do I calculate hours between two times?

To calculate the number of hours between two times:Subtract the starting time from the ending time. Do you have any seconds or minutes after the subtraction? If so: Take seconds, divide them by 60, and add the result to the minutes.

How do you calculate minutes between two times?

To calculate the total minutes between two times: Make sure to convert both times to 24-hour time format. Take starting time and subtract it from ending time. Multiply the hours by 60 to convert it into minutes and add it to any amount of minutes you have left after the subtraction.


2 Answers

use TimeSpan, no need to use dates

var start = TimeSpan.Parse(start.Text);
var end = TimeSpan.Parse(end.Text);

TimeSpan result = end - start;
var diffInMinutes = result.TotalMinutes();
like image 41
Binary Worrier Avatar answered Sep 27 '22 17:09

Binary Worrier


Use TimeSpan class, and Subtract method of DateTime.

        DateTime t1 = Convert.ToDateTime(textBox1.Text);
        DateTime t2 = Convert.ToDateTime(textBox2.Text);
        TimeSpan ts = t1.Subtract(t2);
like image 60
Mitja Bonca Avatar answered Sep 27 '22 19:09

Mitja Bonca