-2

I wonder how I can get the duration between 2300 and 0100, which should be 0200, but it returns 2200. Im working on an application with Xamarin.Forms and use two TimePickers which returns a TimeSpan.

private TimeSpan CalculateDuration()
{
  var result = timePickerEnd.Time.Subtract(timePickerStart.Time);
  return result.Duration();
}

As long as the startTime is smaller then the endTime, everything works fine. But if someone starts something at 2300 and ends at 0100 it returns 22. I wonder if anyone have some guidelines how i should attack this problem.

user2236165
  • 741
  • 2
  • 11
  • 24
  • 4
    what is the type of `timePickerStart` and `timePickerEnd` because they are not `DateTime` (it has no property `Time`)? (Works fine with `DateTime`: http://rextester.com/WRYIC93965) – Jamiec Jan 06 '15 at 13:13
  • 4
    Its been a while since i left elementary schools, still I think that 23 hours minus one hour is 22 hour and C# is correct. – Ondrej Svejdar Jan 06 '15 at 13:13
  • The type is a TimeSpan, since I work with a TimePicker in Xamarin.Forms. And if startTime is 0100 and endTime is 2300, the duration is 2200. Thats correct. However if the startTime is 2300 and the endTime is 0100 the duration is still 2200. If it wasnt for the duration method it would be -2200. Thats why I asked if someone have some tips how I could svolve this problem. – user2236165 Jan 06 '15 at 13:28

1 Answers1

2

You have specific rules, you have to implement them:

var ts1 = timePickerStart.Time;
var ts2 = timePickerEnd.Time;
var difference=  ts2.Subtract(ts1);
if(ts1 > ts2)
{
    difference= difference.Add(TimeSpan.FromHours(24));
}
return difference;

Because the rule that you've failed to articulate (that I've guessed at above) is that "if the start time is greater than the end time, then they should be interpreted as occurring on successive days" - which is by no means a universal assumption that the system should make.

Damien_The_Unbeliever
  • 234,701
  • 27
  • 340
  • 448