Sunday, 4 August 2013

Find number of days between two dates.


+ (int)daysBetweenFromDate:(NSDate*)fromDateTime toDate:(NSDate*)toDateTime
{
    NSDate *fromDate;
    NSDate *toDate;

    //initialize the calender
    NSCalendar *calendar = [NSCalendar currentCalendar];

    //Returns by reference the starting time and duration of a given calendar unit that contains a given date.
    [calendar rangeOfUnit:NSDayCalendarUnit startDate:&fromDate
                 interval:NULL forDate:fromDateTime];
    
    [calendar rangeOfUnit:NSDayCalendarUnit startDate:&toDate
                 interval:NULL forDate:toDateTime];

    //Returns, as an NSDateComponents object using specified components, the difference between two supplied dates.
    NSDateComponents *difference = [calendar components:NSDayCalendarUnit
                                               fromDate:fromDate toDate:toDate options:0];
    
    return [difference day];
}

No comments:

Post a Comment