Days difference calculation gives wrong results.

Discussion in 'Mac Programming' started by newformac, Jun 11, 2011.

  1. newformac, Jun 11, 2011
    Last edited by a moderator: Jun 11, 2011

    newformac macrumors regular

    May 24, 2011
    I am calculating days difference between two dates as below:

    but in result its give day 1 but exactly its 31 days.

    NSString * lastdate_str=@"2010-06-12";
    NSString * todayString=@"2010-07-13";
    NSDate *lastDate = [dateFormatter dateFromString:lastdate_str];
    NSDate *todaysDate = [dateFormatter dateFromString:todayString];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *differenceComponents = [calendar components:NSMonthCalendarUnit | NSDayCalendarUnit fromDate:lastDate toDate:todaysDate options:0];
    int daysDifference = [differenceComponents day];
    please help me for this.

    thanks in advance.
  2. kainjow Moderator emeritus


    Jun 15, 2000
    You're using NSMonthCalendarUnit as well, so the NSDateComponents value will will give you the number of months, plus the remaining number of days. If you *only* want days, remove NSMonthCalendarUnit and just use NSDayCalendarUnit.

    From the documentation:
  3. newformac thread starter macrumors regular

    May 24, 2011

Share This Page