2016-11-23 14 views
0

私は以下の方法を使用して、時間差を分単位で取得していますが、負の値になります。私は数分で日付以下これら二つの違いを計算したい日付iosの時間差(分)

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; 

  • 日付1:2016年11月23日7時39分44秒0000

    私は、次のコードを使用しています

  • date2の:私は-34を取得していた結果2016年11月23日午前8時13分44秒0000

+0

戻りABS(RES)。 – Darshana

答えて

0

fromDateは以前の日付が含まれていますし、toDate意志があなたはそれが間違ってこの

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

あなたはこれを交換する必要があり、この

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

に変更渡しているNSDateComponentsで後日が含まれています

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

whi ch日付は前者で、差の絶対値を返すだけです。それは常にあなたにプラスの価値を与えます。

return abs(res);