I want to convert the timespan diff value always positive .
My code is here :
TimeSpan lateaftertime = new TimeSpan();
lateaftertime = lateafter - Convert.ToDateTime(intime);
I want to get the result of lateaftertime
always positive.
I want to convert the timespan diff value always positive .
My code is here :
TimeSpan lateaftertime = new TimeSpan();
lateaftertime = lateafter - Convert.ToDateTime(intime);
I want to get the result of lateaftertime
always positive.
You can use lateaftertime.Duration()
to get a non-negative span.
Duration()
that would give an absolute TimeSpan
–
Slowwitted You could use Math.Abs():
lateaftertime = new TimeSpan(Math.Abs(lateaftertime.Ticks));
User V4Vendetta made the right call in a comment though. Use the TimeSpan.Duration property, it always returns the absolute value.
OK, I'll assume you're using C# because it looks that way.
The -
operator on the TimeSpan
class has been overloaded, so all you need to do is prefix your calculation with -
as you would if you were performing the conversion on an integer. Here is some code that you can run in a Console App:
var inTime = "19-Jan-2012 21:00";
var lateAfter = Convert.ToDateTime("19-Jan-2012 20:00");
TimeSpan lateAfterTime = lateAfter - Convert.ToDateTime(inTime);
var positiveLateAfterTime =
lateAfterTime < TimeSpan.Zero
?
-lateAfterTime
:
lateAfterTime;
Console.WriteLine(positiveLateAfterTime.ToString());
© 2022 - 2024 — McMap. All rights reserved.