0

I'm calculating the duration time between a startTime and endTime and am using the following code to get the time interval between two NSDates

    NSTimeInterval duration = [self.endTime timeIntervalSinceDate:self.startTime];
    NSLog(@"interval: %f", duration);

However, the NSLog statement tells me that the duration is wrong. The dates are derived from a datePicker. For example, when I set the start date to Jun 19, 2013 9:15pm and end date to Jun 19, 2013, 2013 916pm (one minute later), the duration logged is 15.00000 instead of 60.00000.

Why is this? How can I get the correct duration between two dates?

EDIT

I did some more logging and logged the start date and the end time. Here's the NSLog statement

NSLog(@"interval: %f for %@ to %@", duration, self.startTime, self.endTime);

and here's what gets logged:

interval: 15.000000 for 2013-06-19 04:52:45 +0000 to 2013-06-19 04:53:00 +0000

For some reason the start date from the datePicker is setting the seconds to 45 even though the date picker just says 4:52. How can I fix this?

Also, as a note, the same datePicker is used to choose both dates if that matters at all.

user1529956
  • 735
  • 2
  • 10
  • 24
  • Update your log statement to also log `self.endTime` and `self.startTime`. Update your question with the actual output from this updated log statement. – rmaddy Jun 19 '13 at 18:38
  • Those two times are 15 seconds apart. Why do you expect a different result? – rmaddy Jun 19 '13 at 18:49
  • @rmaddy after logging the start and end time, I realized my problem is not actually the duration but the dates set by the datePicker. Any idea how to get it to return a date with 0 seconds? I'm not sure why the datePicker gives a date with 45 seconds at one time and 0 seconds at another time. – user1529956 Jun 19 '13 at 18:53

1 Answers1

1

The issue actually appears to be a "feature" of UIDatePicker when selecting a time. Even though it only shows hours and minutes, the time includes whatever the current seconds happen to be. Personally I think this is a bug in the date picker.

Your best solution is to tweak the value that you get back from the date picker.

Here's one way to ensure the date has 0 seconds:

- (NSDate *)truncateSeconds:(NSDate *)pickerDate {
    NSTimeInterval secs = [pickerDate timeIntervalSinceReferenceDate];
    long truncated = secs / 60 * 60;

    return [NSDate dateWithTimeIntervalSinceReferenceDate:truncated];
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579