Learn to write readable code. There are at least 4 things that make your code hard to read:
#1 You don't use indentation
#2 You don't add some extra blank lines at appropriate locations.
#3 You declare variable you never use
#4 You have many variable that duplicate other variables.
Also:
* You have to handle wrong user inputs by using
TryParse
and take the appropriate action when the input is bad.
* In real application, you have to take into account the fact that user might want to enter time in 24 hours format too.
* You probably does not correctly handle extra time that ends between 12:00AM and 12:59AM inclusively as you systematically add 12 hours.
* The code for each case would be similar so you should have functions that handle common code.
* How extra is intended to be use is not clear as all other cases appears to work in pairs... but for extra you systematically add 12 hours.
* Your output format is probably not the expected one. You probably want to use
@"hh\:mm"
instead.
*
TimeSpan(0)
is useless as there is already a property for that:
TimeSpan.Zero
. If make the code more efficient and more readable.
From your question is is not clear what is the desired output format. It seems that you want to output a time span so the military vs standard time does not seems to fit your code!
Here is the refactored code that does essentially the same things as your (except that I test for bad inputs):
DateTime amtimein, amtimeout;
if (!DateTime.TryParse(txt1.Text + "AM", out amtimein))
{
}
else if (!DateTime.TryParse(txt2.Text + "AM", out amtimeout))
{
}
else
{
TimeSpan diff = amtimeout.Subtract(amtimein);
if (diff < TimeSpan.Zero)
{
diff += TimeSpan.FromHours(12);
}
var txtm.Text = diff.ToString(@"hh\:mm");
}