TimeSpan difference from negative to positive

TimeSpan Earlybeforetime = new TimeSpan(); Earlybeforetime = earlybefore.Subtract(Convert.ToDateTime(outtime); 

Sometimes it returns a negative value. How to convert a value that will always be positive?

+4
source share
3 answers

You can use Negate() to change a negative value to a positive

From MSDN

If the date and time of the current instance is higher than the value, the method returns a TimeSpan object that represents the negative span time. That is, the value of all its non-zero properties (such as Days or ticks) is negative.

So you can call the Negate method depending on which value is larger and get a positive Timespan

Say we have startDate and endDate (endDate is larger than startDate), so when we do startDate.Subtract(endDate) we get a negative Timespan . Therefore, based on this check, you can convert a negative value. So if your waiting time is ahead sooner, it will give you a negative TimeSpan

EDIT

Please check Duration() in Timespan , this should mean absolute value

Earlybeforetime.Duration()

+14
source

Negative values ​​are returned when your earliest early time is earlier , it is a wait time. if you want to have an absolute "distance" between two points in time, you can use the TimeSpan.Duration method, for example:

 TimeSpan first = TimeSpan.FromDays(5); TimeSpan second = TimeSpan.FromDays(15); TimeSpan final = first.Subtract(second).Duration(); Console.WriteLine(final); 

this method will return the absolute value of TimeSpan.

+7
source
 var startTime = new TimeSpan(6, 0, 0); // 6:00 AM var endTime = new TimeSpan(5, 30, 0); // 5:30 AM var hours24 = new TimeSpan(24, 0, 0); var difference = endTime.Subtract(startTime); // (-00:30:00) difference = (difference.Duration() != difference) ? hours24.Subtract(difference.Duration()) : difference; // (23:30:00) 

can also add the difference between dates if we compare two different dates with 24 hours new TimeSpan(24 * days, 0, 0)

0
source

Source: https://habr.com/ru/post/1391794/


All Articles