View Full Version : Days difference calculation gives wrong results.

Jun 11, 2011, 02:59 AM
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.

Jun 11, 2011, 11:31 AM
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:
...generally larger components will be computed before smaller components; for example, in the Gregorian calendar a result might be 1 month and 5 days instead of, for example, 0 months and 35 days.

Jun 13, 2011, 01:31 AM