Caladan
Caladan

Reputation: 33

The difference between 2 timespans if the second one is on the next day

Let's say I have 2 timespans (24h format) in C#:

TimeSpan start = TimeSpan.Parse("22:11:00");
TimeSpan end = TimeSpan.Parse("01:54:12");
TimeSpan duration = end - start;

The problem is that the duration in this case is a negative number, far from the correct result. How to get the correct duration?

Upvotes: 1

Views: 96

Answers (3)

ispiro
ispiro

Reputation: 27673

TimeSpan duration = end - start;

Not: start - end .

Upvotes: 0

Yurii N.
Yurii N.

Reputation: 5703

You can use Duration() method:

TimeSpan duration = (start - end).Duration();

Upvotes: 1

Nkosi
Nkosi

Reputation: 247108

Take a look at the following Unit test

[DataRow("16:00", "01:00", "09:00")]
[DataRow("16:00", "21:00", "05:00")]
public void CalculateDuration(string open, string close, string expected) {
    var begin = TimeSpan.Parse(open);
    var end = TimeSpan.Parse(close);

    var actual = end < begin ? (TimeSpan.FromHours(24) - begin) + end : end - begin;

    Assert.AreEqual(TimeSpan.Parse(expected), actual);
}

Upvotes: 1

Related Questions