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
  • 52,040
  • 14
  • 137
  • 178
Jacob Clark
  • 3,317
  • 5
  • 32
  • 61

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
  • 52,040
  • 14
  • 137
  • 178