Search code examples
objective-cnsdateuilocalnotificationnsdatecomponents

How to create a date object for tomorrow at 8am


I am normally pretty good with this, but I am having trouble with the NSDate object. I need a NSDate object set for tomorrow at 8am (relatively). How would I do this and what is the simplest method?


Solution

  • Here's how WWDC 2011 session 117 - Performing Calendar Calculations taught me:

    NSDate* now = [NSDate date] ;
    
    NSDateComponents* tomorrowComponents = [NSDateComponents new] ;
    tomorrowComponents.day = 1 ;
    NSCalendar* calendar = [NSCalendar currentCalendar] ;
    NSDate* tomorrow = [calendar dateByAddingComponents:tomorrowComponents toDate:now options:0] ;
    
    NSDateComponents* tomorrowAt8AMComponents = [calendar components:(NSEraCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:tomorrow] ;
    tomorrowAt8AMComponents.hour = 8 ;
    NSDate* tomorrowAt8AM = [calendar dateFromComponents:tomorrowAt8AMComponents] ;
    

    Too bad iOS doesn't have [NSDate dateWithNaturalLanguageString:@"tomorrow at 8:00 am"]. Thanks, rmaddy, for pointing that out.