At its simplest, you can do this:
DateTime time1 = DateTime.Parse(TextBox1.Text);
DateTime time2 = DateTime.Parse(TextBox2.Text);
TimeSpan ts = time2 - time1;
int hours = ts.Hours + (ts.Days * 24);
int minutes = ts.Minutes;
This makes a lot of assumptions, however. Assumptions:
1. Textboxes have actual time values
2. Time2 is larger than Time1
If you can verify the assumptions will always be correct, you can roll with
this. If not, you need a safety net. It looks more like this:
DateTime time1, time2;
TimeSpan ts;
bool time1Okay = DateTime.TryParse(TextBox1.Text, out time1);
bool time2Okay = DateTime.TryParse(TextBox2.Text, out time2);
if ((time1Okay) && (time2Okay))
{
int compare = DateTime.Compare(time1, time2);
if (compare < 0)
{
//time 1 is smaller than time 2
ts = time2 - time1;
}
else
{
//time 1 is bigger than time 2
ts = time1 - time2;
}
//Calculate values
int hours = ts.Hours + (ts.Days * 24);
int minutes = ts.Minutes;
//Display Differences here
}
else
{
//Alert user time value(s) is/are bad
}
If you also want seconds, you can do this:
//Calculate values
int hours = ts.Hours + (ts.Days * 24);
int minutes = ts.Minutes;
int seconds = ts.Seconds;
But perhaps you like to go about this the hard way?
double totalSeconds = ts.TotalSeconds;
double workingMinutes = (totalSeconds / 60);
int seconds = (int)(workingMinutes - (int)workingMinutes);
int hours = (int)(workingMinutes / 60);
int minutes = (int)(workingMinutes - (hours *60));
You can also go from the other direction, but you will end up with rounding
errors:
double totalHours = ts.TotalHours;
int hours = (int)totalHours;
double workingMinutes = (totalHours - hours) * 60;
int minutes = (int)workingMinutes;
int seconds = (int)((workingMinutes - minutes) * 60);
Have fun!
--
Gregory A. Beamer
MVP, MCP: +I, SE, SD, DBA
Subscribe to my blog
http://feeds.feedburner.com/GregoryBeamer#
or just read it:
http://feeds.feedburner.com/GregoryBeamer
********************************************
| Think outside the box! |
********************************************