Search code examples
iphonesdknsdatedatenscalendar

Is my Contact's birthday in next 10 days


I am trying to calculate whether any of my Address Book's contacts have a birthday in the next 10 days. There's plenty of code on line to compare dates, but I only want to compare day and month. For example, if a contact was born 05/01/1960 (and assuming today is 04/24/2011), then I only want to calculate that there are only six days till their birthday. Help appreciated.


Solution

  • Change the birthday to this year (or next year if the birthday was already in this year) and calculate with NSDateComponents and NSCalendar.

    Looks a bit complicated, but you could do it like this:

    NSDate *birthDay = ... // [calendar dateFromComponents:myBirthDay];
    
    NSCalendar *calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
    
    NSDateComponents *thisYearComponents = [calendar components:NSYearCalendarUnit fromDate:[NSDate date]];
    NSDateComponents *birthDayComponents = [calendar components:NSMonthCalendarUnit|NSDayCalendarUnit fromDate:birthDay];
    [birthDayComponents setYear:[thisYearComponents year]];
    
    NSDate *birthDayThisYear = [calendar dateFromComponents:birthDayComponents];
    
    NSDateComponents *difference = [calendar components:NSDayCalendarUnit fromDate:[NSDate date] toDate:birthDayThisYear options:0];
    if ([difference day] < 0) {
        // this years birthday is already over. calculate distance to next years birthday
        [birthDayComponents setYear:[thisYearComponents year]+1];
        birthDayThisYear = [calendar dateFromComponents:birthDayComponents];
        difference = [calendar components:NSDayCalendarUnit fromDate:[NSDate date] toDate:birthDayThisYear options:0];
    }
    
    
    NSLog(@"%i days until birthday", [difference day]);