Question

That's not a typo (at least not on my part, anyways.)

One of the defined NSCalendarUnits are a NSCalendarCalendarUnit. Can anyone explain what that is or how you would use it?

For example, I'd like to calculate the number of days between dates, which potentially took place in different eras. Apple provides this code for finding the number of days between dates within an era as such (it's implemented as a category on NSCalendar, thus self refers to an NSCalendar):

NSInteger start = [self ordinalityOfUnit:NSDayCalendarUnit inUnit:NSEraCalendarUnit forDate:startDate];
NSInteger end   = [self ordinalityOfUnit:NSDayCalendarUnit inUnit:NSEraCalendarUnit forDate:endDate];
return end - start;

Is the proper way of modifying this to accept the possibility of different eras by replacing NSEraCalendarUnit with NSCalendarCalendarUnit?

Was it helpful?

Solution

An instance of NSDateComponents can include a calendar. This component was added in iOS 4.0 and OS X 10.7:

iOS Note: In iOS 4.0 and later, NSDateComponents objects can contain a calendar, a timezone, and a date object. This allows date components to be passed to or returned from a method and retain their meaning.

You can pass NSCalendarCalendarUnit to -[NSCalendar components:fromDate:] to have it include the calendar in the returned NSDateComponents.

UPDATE

If you want to compute the number of days between two dates, use -[NSCalendar components:fromDate:toDate:options:]. You may need to construct the two NSDate objects first, using dateFromComponents:.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top