Difference between two NSDate objects -- Result also a NSDate Difference between two NSDate objects -- Result also a NSDate ios ios

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);


If you subtract 12/12/2001 from 05/05/2002 what will be the date? The chronological distance between two dates can't be a date, it's alway some kind of interval. You can use timeIntervalSinceDate: to calculate the interval.

To localize you can try the following steps:


From NSDate class reference, you have instance methods to do these -

  1. How to compare two NSDate variables? Ans: isEqualToDate:
  2. How to find difference between two NSDate variables? Ans: timeIntervalSinceDate:
  3. How to get each separate value of minute, hours and days from NSDate variable? links