TimeSpan difference from negative value to positive conversion
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 difference between the dates if we compare two different dates times the 24 hours new TimeSpan(24 * days, 0, 0)
You could use Negate()
to change the negative value to positive
From MSDN
If the date and time of the current instance is earlier than value, the method returns a TimeSpan object that represents a negative time span. That is, the value of all of its non-zero properties (such as Days or Ticks) is negative.
So you could call the Negate method depending on which value is greater and obtain a positive Timespan
Say we have startDate
and endDate
(endDate is greater than startDate), so when we do
startDate.Subtract(endDate)
we would get a negative TimeSpan
. So based on this check you could convert the negative value. So if your outtime is ahead of earlybefore it would give you a negative TimeSpan
EDIT
Please check Duration()
of the TimeSpan
this should give you the absolute value always
Earlybeforetime.Duration()
Negative values are returned when yours Earlybeforetime is earlier that outtime. if you want to have absolute "distance" between two points in time, you can use TimeSpan.Duration method, e.g:
TimeSpan first = TimeSpan.FromDays(5);
TimeSpan second = TimeSpan.FromDays(15);
TimeSpan final = first.Subtract(second).Duration();
Console.WriteLine(final);
this method will return absolute TimeSpan value.