-3

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?

Rince Thomas
  • 4,158
  • 5
  • 25
  • 44
  • 1
    Refer http://stackoverflow.com/questions/4371757/how-can-i-calculate-the-difference-between-two-dates – Rince Thomas Jul 01 '16 at 06:06
  • i have tried it though –  Jul 01 '16 at 06:13
  • Those whole code can be simplified as `NSDateComponents *currentDateComponent = [[NSCalendar currentCalendar] components:NSCalendarUnitDay fromDate:[NSDate date] toDate:picker.date options:0];` – Midhun MP Jul 01 '16 at 06:24

1 Answers1

1

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];
Saraswati
  • 1,516
  • 1
  • 14
  • 21