1

I have observed the documentation for a particular method which gets an interval between a date:

- (NSTimeInterval)timeIntervalSinceDate:(NSDate *)anotherDate

What I need this this method (or an alternative) to provide me with the Years and Days since a given date.

How would I be able to calculate this? I could use days/365 and then the remainder be the days but this isn't very accurate and I need accuracy for this.

Thanks!

vikingosegundo
  • 51,574
  • 14
  • 135
  • 174
Jacob Clark
  • 3,087
  • 4
  • 29
  • 58

1 Answers1

3

using - (NSTimeInterval)timeIntervalSinceDate:(NSDate *)anotherDate will fail in many cases (Daylight saving times, leap seconds,…), you should take a calendar into account, as those are aware this.

NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorianCalendar components:(NSDayCalendarUnit |NSYearCalendarUnit )
                                                    fromDate:startDate
                                                      toDate:[NSDate date]
                                                     options:0];

NSLog(@"%ld", [components day]);
NSLog(@"%ld", [components year]);
vikingosegundo
  • 51,574
  • 14
  • 135
  • 174