Skip to content

Instantly share code, notes, and snippets.

@flashfabrixx
Created May 8, 2014 09:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save flashfabrixx/f0a1d10a794e5a574d1c to your computer and use it in GitHub Desktop.
Save flashfabrixx/f0a1d10a794e5a574d1c to your computer and use it in GitHub Desktop.
Method returns a string containing the number of days since a given reference date
- (NSString *)daysSinceDate:(NSDate *)referenceDate
{
NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSCalendarUnit units = NSYearCalendarUnit | NSMonthCalendarUnit | NSWeekCalendarUnit | NSWeekdayCalendarUnit | NSDayCalendarUnit;
NSDateComponents *components = [gregorian components:units fromDate:referenceDate toDate:today options:0];
NSInteger days = [components day];
NSInteger years = [components year];
for (NSInteger j = 0; j < years; j++) {
components.year = j;
NSDate *newDate = [gregorian dateByAddingComponents:components toDate:referenceDate options:0];
NSRange rangeDays = [gregorian rangeOfUnit:NSMonthCalendarUnit
inUnit:NSYearCalendarUnit
forDate:newDate];
for (NSInteger i = 0; i < rangeDays.length; i++) {
components.month = i;
NSDate *newMonth = [gregorian dateByAddingComponents:components toDate:referenceDate options:0];
NSRange rangeYears = [gregorian rangeOfUnit:NSDayCalendarUnit
inUnit:NSMonthCalendarUnit
forDate:newMonth];
days += rangeYears.length;
}
}
return days;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment