Saturday, May 28, 2011

Calculate number of days between two dates in iPhone SDK

Hello Friends,

Today we will focus on another important issue while developing iPhone application. Most of the application contains date picker to select and display date in iPhone. Sometimes it is required to get number of day between two dates. For this calculation use following code.

To get correct number of days dates should be in yy-mm-dd format. For this use following code.

- (int) daysToDate:(NSDate*) endDate
{
    NSDateFormatter *temp = [[NSDateFormatter alloc] init];
    [temp setDateFormat:@"yyyy-MM-dd"];
    NSDate *stDt = [temp dateFromString:[temp stringFromDate:[NSDate date]]];
    NSDate *endDt =  [temp dateFromString:[temp stringFromDate:endDate]];
    [temp release];
    unsigned int unitFlags = NSDayCalendarUnit;
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *comps = [gregorian components:unitFlags fromDate:endDt  toDate:stDt options:0];
    int days = [comps day];
   
    [gregorian release];
    return days;
}


Now use the following function where you want to get day difference.

NSString *str =[NSString stringWithFormat:@"%@ 00:00:00",[strdate substringToIndex:10]];
   NSDateFormatter *df = [[NSDateFormatter alloc] init];
   [df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
   NSDate *dd = [df dateFromString:str];
   int d = [self daysToDate:dd];

Pass date in yy-mm-dd hh:mm:ss format. Example: 2011-05-28 00:00:00. Date should be in this format in str variable.

No comments:

Post a Comment