Reputation: 33
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
Reputation: 5703
You can use Duration() method:
TimeSpan duration = (start - end).Duration();
Upvotes: 1
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