iphonecocoa-touchnsdatefoundationkit

NSDate -dateWithNaturalLanguageString: on iPhone?


In the iPhone docset for NSDate, in the discussion area they discuss -dateWithNaturalLanguageString:locale:, however they don't document the method elsewhere on the page.

I've used the method before for iPhone and it worked just fine, although I got warnings. Now that I'm building with -Werror (which I should have been doing all along ^_^) I've run into a warning with this.

How would I replace the following lines of code?

NSDate *today = [NSDate dateWithNaturalLanguageString:@"today at 23:59:59"];
NSDate *tomorrow = [NSDate dateWithNaturalLanguageString:@"tomorrow at 23:59:59"];

Solution

  • One way to do this is with NSCalendar and NSDateComponents.

    To get today at 23:59:59:

    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    NSDateComponents *comps = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit 
                                          fromDate:date];
    
    [comps setHour:23];
    [comps setMinute:59];
    [comps setSecond:59];
    
    NSDate *today = [calendar dateFromComponents:comps];
    

    To get tomorrow at 23:59:59:

    NSDate *now = [NSDate dateWithTimeIntervalSinceNow:24 * 60 * 60]; // 24h from now
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    NSDateComponents *comps = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit 
                                          fromDate:date];
    
    [comps setHour:23];
    [comps setMinute:59];
    [comps setSecond:59];
    
    NSDate *tomorrow = [calendar dateFromComponents:comps];