Search code examples
iosobjective-cnsdatenscalendar

What is NSCalendar's rangeOfUnit:startDate:interval:forDate really doing?


I'm converting some of my really old code from Objective C to Swift, and I ran across this monstrosity. I can't figure out exactly what I was doing here. Looking at the documentation on that rangeOfUnit method I'm left scratching my head.

It seems like I'm just finding out how many days exist between those two dates, but that seems like a really strange way to do it.

NSDate *fromDate, *toDate;
[self.calendar rangeOfUnit:NSCalendarUnitDay startDate:&fromDate interval:0 forDate:event.startDate];
[self.calendar rangeOfUnit:NSCalendarUnitDay startDate:&toDate interval:0 forDate:event.endDate];

NSInteger difference = labs([self.calendar components:NSCalendarUnitDay fromDate:fromDate toDate:toDate options:0].day) + 1;

Solution

  • The method rangeOfUnit calculates the start of the calendar unit (here day) that contains the given dates respectively which means midnight. The pointers fromDate and toDate contain the results on return. A pointer for the interval parameter would return 86400 which is the NSTimeInterval of the calendar unit.

    NSCalendar has a method to do the same thing much easier:

    NSDate *fromDate = [self.calendar startOfDayForDate:event.startDate];