Tarasov
Tarasov

Reputation: 3685

How I get a positive TimeSpan If the second DateTime is bigger then the first?

Hi I have a Problem with the TimeSpan in C#.

In my Application I calculate the difference of two time. How this ->

12:00:30 - 12:00:00 = 00:00:30 

but my problem is if the second time is bigger then the first time...I get a negative number :(

1:00:00 - 23:00:00 = -22:00:00 

But I want a positive number how this -->

1:00:00 - 23:00:00 -> 2:00:00 

here my code:

private static int GetTimeSpan(string Out, string In) {

            try
            {
                TimeSpan diff = DateTime.Parse(In) - DateTime.Parse(Out);

                double TotalSec = diff.TotalSeconds;

                return (int)TotalSec;
            }
            catch (Exception)
            {
                return 0;
            }

        }

Upvotes: 0

Views: 1412

Answers (3)

Andrei
Andrei

Reputation: 56688

You can check the result of calculation, and if it is negative - add 24 hours to it to get complement time span:

TimeSpan diff = DateTime.Parse(In) - DateTime.Parse(Out);
if (diff.TotalSeconds < 0) {
    diff = diff.Add(new TimeSpan(24, 0,0));
}

Upvotes: 0

Tarec
Tarec

Reputation: 3255

How about

 DateTime dt1 =  DateTime.Parse(In);
 DateTime dt2 =  DateTime.Parse(Out);
 TimeSpan diff = (dt1>dt)? dt1- dt2 : dt2 - dt1; 

Upvotes: 0

Jon
Jon

Reputation: 437386

You are looking for TimeSpan.Duration(), which returns the absolute value of a TimeSpan:

TimeSpan diff = (DateTime.Parse(In) - DateTime.Parse(Out)).Duration();

Upvotes: 6

Related Questions