0

i am using following method to get date time difference in minutes it giving me negative value .

I am using following code :

NSCalendar *gregorian = [[NSCalendar alloc]
                         initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

NSUInteger unitFlags = NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitMinute;

NSDateComponents *components = [gregorian components:unitFlags
                                            fromDate:dt2
                                              toDate:dt1 options:0];
NSInteger months = [components month];
NSInteger days = [components day];
NSInteger minutes = [components minute];

NSLog(@"months %ld",(long)months);
NSLog(@"days %ld",(long)days);
NSLog(@"minutes %ld",(long)minutes);

int res = (int)minutes;
NSLog(@"int minutes %d",res);

return res;

I want to calculate difference between these two below date in minutes:

  • date1:2016-11-23 07:39:44 +0000
  • date2:2016-11-23 08:13:44 +0000

As a result I'm getting -34.

TobiMcNamobi
  • 4,687
  • 3
  • 33
  • 52
puja
  • 209
  • 1
  • 15

3 Answers3

1

You need to replace with this :

NSDateComponents *components = [gregorian components:unitFlags
                                            fromDate:dt1
                                              toDate:dt2 options:0];
KKRocks
  • 8,222
  • 1
  • 18
  • 84
0

fromDate will contain an earlier date and toDate will contains later date in NSDateComponents you are passing it wrongly change this

NSDateComponents *components = [gregorian components:unitFlags
                                            fromDate:dt2
                                              toDate:dt1 options:0];

to this

NSDateComponents *components = [gregorian components:unitFlags
                                            fromDate:dt1
                                              toDate:dt2 options:0];
Rajat
  • 10,977
  • 3
  • 38
  • 55
0

If you don't know which date is former, just return absolute value of difference. That will always give you positive value.

return abs(res); 
PlusInfosys
  • 3,416
  • 1
  • 19
  • 33