Difference between two NSDate objects — Result also a NSDate

NSDate represents an instance in time, so it doesn’t make sense to represent an interval of time as an NSDate. What you want is NSDateComponents:

NSDate *dateA;
NSDate *dateB;

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay
                                           fromDate:dateA
                                             toDate:dateB
                                            options:0];

NSLog(@"Difference in date components: %i/%i/%i", components.day, components.month, components.year);

Leave a Comment