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!

4

1 回答 1

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]);
于 2013-02-17T13:51:36.027 回答