Learner Learner - 5 months ago 16
Objective-C Question

Finding the difference between two dates always prints 10

Following is my code to get current date.

-(NSString *) getCurrentDate {
NSDateFormatter *dateformater = [[NSDateFormatter alloc]init];
[dateformater setDateFormat:@"dd-MMM-yyyy"];
NSString *today=[dateformater stringFromDate:[NSDate date]];
return today;
}


Im using the following code to find the difference between current date and the date selected from pickerview

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"dd-MMM-yyyy"];
NSString *date = [dateFormat stringFromDate:picker.date];
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:GregorianCalendar];
NSCalendarUnit unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:@"dd-MMM-yyyy"];
NSDate *selectedDate = [f dateFromString:date];
NSDate *currentDate = [f dateFromString:[self getCurrentDate]];
NSDateComponents *currentDateComponent = [gregorianCalendar components:unitFlags fromDate:currentDate toDate:selectedDate options:0];


but the
currentDateComponent.day
always prints the value 10.

whats wrong with my code? how can i be able to find the difference between two dates?

Answer

I think components you are using is wrong it should but only NSCalendarUnitDay My code is returning me correct difference (difference.day).

 NSCalendar *calendar = [NSCalendar currentCalendar];
 NSDateComponents *difference = [calendar components:NSCalendarUnitDay
                                                           fromDate:[NSDate date] toDate:enDate options:0];