Renan Santos
Renan Santos

Reputation: 73

c# - Substracting two times returns negative value

I'm having problems when I'm trying to substract hr2 with hr1 in a specific situation, for example, when hr1 = 13:00 and hr2 = 15:00, ok, the result is 02:00. But when the values are: hr1 = 22:00 and hr2 = 02:00, the result is 20:00. The result should be 04:00.

 TimeSpan ts1 = hr1.Subtract(hr2).Duration();
 TextBox1.Text = ts1.ToString();

How can I solve this problem?

Upvotes: 1

Views: 1021

Answers (3)

Jim D'Angelo
Jim D'Angelo

Reputation: 3952

You are trying to subtract two "spans", or durations, of time--not fixed points in time. What your code is currently saying is, I want to subtract two hours from twenty hours (which is indeed twenty hours). Instead, you need to use DateTimes. The hard part is going to be deciding the date for your timespans. I would rework the code to use DateTimes and preserve the "moments" in time that you are actually attempting to calculate.

Edit: Converting from a TimeSpan to a DateTime can cause you to lose information that affects the outcome of the result:

var ts1 = new DateTime (1, 1, 1, hr1.Hours, hr1.Minutes, hr1.Seconds, hr1.Milliseconds) -
          new DateTime (1, 1, 1, hr2.Hours, hr2.Minutes, hr2.Seconds, hr2.Milliseconds);

is different than:

var ts1 = new DateTime (1, 1, 1, hr1.Hours, hr1.Minutes, hr1.Seconds, hr1.Milliseconds) -
          new DateTime (1, 1, 2, hr2.Hours, hr2.Minutes, hr2.Seconds, hr2.Milliseconds);

or:

var ts1 = new DateTime (1, 1, 2, hr1.Hours, hr1.Minutes, hr1.Seconds, hr1.Milliseconds) -
          new DateTime (1, 1, 1, hr2.Hours, hr2.Minutes, hr2.Seconds, hr2.Milliseconds);

Which is why you need to maintain the "point in time" with a DateTime.

Upvotes: 0

Omaha
Omaha

Reputation: 2292

Invoking Duration() will always result in a positive TimeSpan. The problem is coming from the fact that you are discarding days in your calculation. 22:00-02:00 is 20:00. I believe you are expecting it to be 04:00 because 02:00 represents "tomorrow." If that is what you want, you will need to calculate 22:00-(02:00+24:00) which will give you -04:00, which will become 04:00 when you invoke Duration().

Upvotes: 1

usr
usr

Reputation: 171178

I understand what you want, but how you currently try to achieve it makes no sense. 22 hours minus 20 hours is 2 hours, which is correct.

You probably want this:

new DateTime(1, 1, 2, 2, 0, 0) - new DateTime(1, 1, 1, 22, 0, 0)

You don't want to subtract TimeSpan's, you want to subtract dates (fake dates in this case).

Upvotes: 2

Related Questions