-1

How can I find the difference between two NSDates but ignore the date and only care about the time?

So far, I've found lots of solutions to calculate the difference between NSDates but none that ignore the date and only care about the time.

e.g., The difference betweeen 01/01/01 04:35 PM and 01/09/09 04:36 PM is 1 minute

CodeGuy
  • 28,427
  • 76
  • 200
  • 317

2 Answers2

1

As with everything date calculation related on iOS, NSCalendar has got you covered! Specifically, you want to use components:fromDate:toDate:options: and pass NSWrapCalendarComponents as the option, which will prevent overflowing of components into the higher date components.

JustSid
  • 25,168
  • 7
  • 79
  • 97
0

Try this:

int (^timeFromDate)(NSDate *) = ^(NSDate *date) {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit
                                               fromDate:date];

    return (components.hour * 60 + components.minute) * 60 + components.second;
};
int diff = timeFromDate(date1) - timeFromDate(date2);
Vlad Papko
  • 13,184
  • 4
  • 41
  • 57