Timespan Difference Value Always Positive [duplicate]
Asked Answered
B

3

45

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.

Bestir answered 19/1, 2012 at 7:27 Comment(1)
Note that a difference between 2 TimeOnly values is different-always positive and can be confusing #73040186Astraphobia
G
103

You can use lateaftertime.Duration() to get a non-negative span.

Georgeanngeorgeanna answered 19/1, 2012 at 21:20 Comment(4)
No need for such thing, just use Duration() that would give an absolute TimeSpanSlowwitted
@V4Vendetta: I never knew that. Learn something every day. That's a much nicer approach. I've updated my answer.Georgeanngeorgeanna
Instead of changing your answer, you shoul've asked @Slowwitted to post his and get the deserved recognition. This is totally my personal opinion, but I think it's unfair that you get the upvotes for his answer.Anisotropic
V4Vendetta has always been free to post his own answer. If he'd posted it, I wouldn't have changed my answer.Georgeanngeorgeanna
P
6

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.

Phillida answered 19/1, 2012 at 21:27 Comment(0)
Y
2

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());
Yabber answered 19/1, 2012 at 21:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.