2013-08-24 3 views
0

도트 넷 형식으로 수신되는 두 날짜 간의 차이를 가져오고 싶습니다. 날짜를 NSDate으로 변환했습니다. 그러나 날짜 사이의 정확한 차이 (시간, 분 및 초 필드가 0 임)를 얻을 수 없습니다. 아래의 방법을 사용하고 있습니다. 두 날짜 사이의iOS의 Facebook 댓글과 같은 날짜의 차이 가져 오기

- (NSString*)calculateTimeFromDate :(NSDate*)date { 

NSDate *createdDate; 
NSDate *todayDate; 


NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 

[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"IST"]]; 
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:SS"]; 

NSString *str = [formatter stringFromDate:date]; 
NSString *str1= [formatter stringFromDate:[NSDate date]]; 


createdDate = [formatter dateFromString:str];; 
todayDate = [formatter dateFromString:str1]; 

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


NSUInteger unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit; 

NSDateComponents *components = [gregorian components:unitFlags 
              fromDate:createdDate 
               toDate:todayDate options:0]; 
NSInteger timeDifference = [components day]; 

int days = timeDifference; 
NSString *timeStr; 
if(days>0) { 

    if(days == 1) timeStr = [NSString stringWithFormat:@"%.0i %@",days, LString(@"DAY")]; 
    else   timeStr = [NSString stringWithFormat:@"%.0i %@ ",days, LString(@"DAYS")]; 
    } else { 

    int hours = [components hour]; 
    if(hours >0){ 

     if(hours ==1) timeStr = [NSString stringWithFormat:@"%.0i %@",hours, LString(@"HOUR")]; 
     else   timeStr = [NSString stringWithFormat:@"%.0i %@",hours, LString(@"HOURS")]; 
    } else { 

     int minutes = [components minute]; 
     if(minutes>0) { 

      if(minutes ==1) timeStr = [NSString stringWithFormat:@"%.0i %@",minutes, LString(@"MINUTE")]; 
      else    timeStr = [NSString stringWithFormat:@"%.0i %@",minutes, LString(@"MINUTES")]; 
     } else { 

      int seconds =[components second]; 
      if(seconds >5) timeStr=[NSString stringWithFormat:@"%.0i %@",seconds, LString(@"SECONDS")]; 
      else   timeStr = LString(@"JUST_NOW"); 
     } 
    } 
} 
if(![timeStr isEqualToString:LString(@"JUST_NOW")]) timeStr = [timeStr stringByAppendingFormat:@" %@", LString(@"AGO")]; 
NSLog(@"%@",timeStr); 
return timeStr; 
} 
+1

위의 메서드에서 * str, * str1 정확한 시간과 날짜가 있지만 구성 요소에서 정확한 날짜를 가져올 수 없습니다. 나에게 주어진 실제 날짜는 날짜 (1377216000000)입니다. ur 대답을 제안하십시오 ... – arunit21

+0

-1 그래서 질문은 당신이 게시 한 코드에 관한 것이 아니라 어떻게 NSDate에'Date (1377216000000)'을 돌리는가에 관한 것입니까? 어쩌면 당신은 그 질문을 했어야합니다. 게시 한 코드가 잘 작동합니다. –

+0

날짜를 nsdate 형식으로 변환했습니다. 그러나 날짜를 nslogging하는 동안시 분 구성 요소는 0입니다. 시간과 분, 초를 볼 수있는 날짜 객체에 브레이크 포인트와 호버 커서를 설정할 때. 정확한 문제는 무엇입니까? – arunit21

답변

0

• 차이는 사용하여 계산 될 수있다 - (NSTimeInterval) timeIntervalSinceDate : (있는 NSDate *) anotherDate

NSTimeInterval timeInterval = [todayDate timeIntervalSinceDate:createdDate]; 

을 • 시간, 분, 초에 TimeInterval이 변환합니다.

int minutes = floor(timeInterval/60); 
int seconds = trunc(timeInterval - minutes * 60); 
int hours = minutes/60; 
+0

달력 단위로 계산을 수행하려면 시간 간격을 사용하는 것은 좋지 않습니다. 예를 들어 윤초가있는 경우 계산이 중단 될 수 있습니다. 또한 하루 24 시간을 가정하고 일광 절약 시간이 끝나거나 시작되면 1 시간이 걸릴 것입니다. –

3

이 시도 : https://github.com/jonhocking/PrettyTimestamp

그것은 멋진 문자열로 두 날짜 사이의 차이를 반환있는 NSDate에 정말 멋진 범주,

"전 분"정확히 아닌 경우처럼,이다 당신이 원하는 것은 내가 올바른 방향으로 인도하는 데 도움이 될 것이라고 확신하지만, 원하는대로 문자열을 반환하도록 수정할 수 있습니다.

0

바퀴를 다시 열지 마십시오. 작업에 라이브러리를 사용하십시오.

거기에 몇 가지 github 프로젝트가 있지만 내 의견으로는 FormatterKit이며 AFNetworking의 저자 인 Mattt Thomposon이 만들고 유지 관리하는 프로젝트 중 하나입니다.

잘 작동하며 현지화를 지원합니다.