2010-05-23 2 views
9

글쎄,이 천 번 요청했지만, 어떤 이유로 answeres 정말 일을 해달라고 또는 다른 문제가 있었다 것 같아요 ....오늘 또는 어제에 대한있는 NSDate 비교 어쨌든 여기

내가 무슨 "작업입니다 "

문제 (들) 이제
NSCalendar *calendar = [NSCalendar currentCalendar];  
    NSDate *currentDate = [NSDate date]; 
    NSDateComponents *comps = [[NSDateComponents alloc] init]; 
    // set tomorrow (0: today, -1: yesterday) 
    [comps setDay:0]; 
    NSDate *dateToday = [calendar dateByAddingComponents:comps toDate:currentDate options:0]; 
    [comps setDay:-1]; 
    NSDate *dateYesterday = [calendar dateByAddingComponents:comps toDate:currentDate options:0]; 
    [comps release]; 


NSString *todayString = [self.dateFormatter stringFromDate:dateToday] ; 
NSString *yesterdayString = [self.dateFormatter stringFromDate:dateYesterday] ; 
NSString *refDateString = [self.dateFormatter stringFromDate:info.date]; 

if ([refDateString isEqualToString:todayString]) 
{ 
    cell.title.text = @"Today"; 
} else if ([refDateString isEqualToString:yesterdayString]) 
{ 
    cell.title.text = @"Yesterday"; 
} else 
{ 
    cell.title.text = [self.dateFormatter stringFromDate:info.date]; 
} 

:

쉬운 방법이 바로 날짜 comparinson에 대한 코드의 awefull 많은 것 같다?

가장 중요한 질문은 모든 개체의 릴리스입니다. 짐작 했겠지만, 저는 이것을 UITableViewController에서 사용합니다. ,

//[calendar release]; 
//[currentDate release]; 
//[dateToday release]; 
//[dateYesterday release]; 
//[todayString release]; 
//[yesterdayString release]; 
//[refDateString release]; 

문제는 최대한 빨리이 라인 중 하나의 주석을 해제한다는 것입니다 내 응용 프로그램 충돌을 내가 왜 아무 생각이 : 나는 또한 내 코드에 다음 줄을?! 나는 누군가가 나를 여기에서 가르쳐주기를 바랍니다.

감사합니다.

+1

음, 마지막 비트는 간단합니다 : 당신 이러한 객체를 소유하지 않으므로 배포 할 수 없습니다. comps는 할당 한 유일한 객체입니다. 다른 것들은 모두 autoreleased로 반환되거나 그렇지 않으면 전혀 풀려날 의도가 없습니다. – walkytalky

+0

고마워, 좋은 설명;) – elementsense

답변

12

그것을 할 수있는 가장 쉬운 방법은 날짜의 description를 비교하는 것입니다 :

// Your dates: 
NSDate * today = [NSDate date]; 
NSDate * yesterday = [NSDate dateWithTimeIntervalSinceNow:-86400]; //86400 is the seconds in a day 
NSDate * refDate; // your reference date 

// 10 first characters of description is the calendar date: 
NSString * todayString = [[today description] substringToIndex:10]; 
NSString * yesterdayString = [[yesterday description] substringToIndex:10]; 
NSString * refDateString = [[refDate description] substringToIndex:10]; 

if ([refDateString isEqualToString:todayString]) 
{ 
    cell.title.text = @"Today"; 
} else if ([refDateString isEqualToString:yesterdayString]) 
{ 
    cell.title.text = @"Yesterday"; 
} else 
{ 
    cell.title.text = refDateString; 
} 

당신이 대신 descriptionWithLocale:을 사용할 수 날짜 문자열의 형식을 변경합니다.

+15

설명 메소드의 결과에 의존하지 마십시오. 이는 주로 디버깅 목적으로 존재하며 영구적이거나 되돌릴 수 있음을 보장하지 않습니다. 이 문자열 비교 방법을 사용하려면 명시적인 NSDateFormatter를 사용하여 원하는 정확한 문자열을 생성하십시오. 그러나 NSCalendar로 생성 된 구성 요소를 비교할 수있을 때 약간 과잉이라고 할 수 있습니다. –

+0

GMT에서 현재 사용자의 시간대 오프셋을 벗어나게 될 것입니다 (iOS 7.1에서) 설명 메서드 결과는 GMT로 날짜를 제공합니다. 나를 위해, 그것은 오늘 6 시간 일찍 시작한다는 것을 의미합니다. – dwsolberg

-1

isEqualToDate 메소드를 사용하여 두 개의 NSDate 객체를 비교하고 날짜가 동일한 지 알려주는 bool (예 또는 아니요)을 반환합니다. Apple Documentation을 참조하십시오.

오브젝트를 릴리스하는 경우 - 객관적인 관점에서의 규칙 -c는 메소드 진행 중에 메모리를 할당 한 오브젝트 만 릴리스한다는 것입니다. 코드에서 메모리를 할당하는 유일한 객체는 입니다.이므로 릴리스해야하는 유일한 객체입니다. 할당하지 않은 객체에 대한 메모리를 해제하면 아마도 앱이 다운되는 원인 일 것입니다. 실제로 해당 객체를 할당 한 메소드가 해당 객체를 해제하려고 시도하거나 다른 참조가 객체에 액세스하려고하면 이미 해제 한 것처럼 EXC_BAD_ACCESS 오류가 발생합니다!

그런 출시 줄을 주석 처리하지 말고 스크립트에서 삭제하십시오. 필요 없어!

+1

isEqualToDate :'여기서 작동하지 않습니다. 날짜가 "정확히"동일한 경우에만 "예"를 반환합니다. "이 방법은 날짜 사이의 초초 차이를 감지합니다." (클래스 참조에서) – mohsenr

6

나는 이것이 오래된 질문이라는 것을 알고 있지만, 나 자신과 비슷한 것을하고 있었어.

우선 iOS 4.0 (및 Mac OS 10.6)부터 NSDateFormatter은 상대 날짜를 사용할 수 있으므로 "오늘"과 "어제"가 자동으로 제공됩니다.

2014-03-15 15:26:37.683 TestApp[1293:303] date = Today 

는 그러나, 영업 이익은 오늘이나 어제 나 또한 옆으로 상대 날짜 형식을하고 싶었던 일을 NSDate을 비교하는 방법을 질문했다 : 출력

NSDateFormatter* formatter = [[NSDateFormatter alloc] init]; 
[formatter setTimeStyle:NSDateFormatterNoStyle]; 
[formatter setDateStyle:NSDateFormatterShortStyle]; 
[formatter setDoesRelativeDateFormatting:YES]; 

NSString* dateString = [formatter stringFromDate:[NSDate date]];  
NSLog(@"date = %@", dateString); 

.여기에 내가 NSDate에 카테고리로 구현 해낸 무엇 :

@implementation NSDate (IsToday) 

- (BOOL) isToday 
{ 
    NSCalendar* calendar = [NSCalendar currentCalendar]; 

    // Components representing the day of our date. 
    NSDateComponents* dateComp = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit 
              fromDate:self]; 
    NSDate* date = [calendar dateFromComponents:dateComp]; 

    // Components representing today. 
    NSDateComponents* todayComp = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit 
               fromDate:[NSDate date]]; 
    NSDate* todayDate = [calendar dateFromComponents:todayComp]; 

    // If the dates are equal, then our date is today. 
    return [date isEqualToDate:todayDate]; 
} 

@end 

내가 오늘 피조물의 시간을 표시 할 수 있도록이가하고 싶었던 이유는, 오늘 생성되지 사물의 날짜 - Mail.app가 메시지의 날짜를 표시하는 것과 비슷합니다. 그것은 다음과 같습니다

- (NSString*) postDateToString:(NSDate*)aDate 
{ 
    static NSDateFormatter* todayFormatter = nil; 
    if(todayFormatter == nil) { 
     todayFormatter = [[NSDateFormatter alloc] init]; 
     [todayFormatter setTimeStyle:NSDateFormatterShortStyle]; 
     [todayFormatter setDateStyle:NSDateFormatterNoStyle]; 
    } 

    static NSDateFormatter* notTodayFormatter = nil; 
    if(notTodayFormatter == nil) { 
     notTodayFormatter = [[NSDateFormatter alloc] init]; 
     [notTodayFormatter setTimeStyle:NSDateFormatterNoStyle]; 
     [notTodayFormatter setDateStyle:NSDateFormatterShortStyle]; 
     [notTodayFormatter setDoesRelativeDateFormatting:YES]; 
    } 

    NSDateFormatter* formatter = notTodayFormatter; 

    if([aDate isToday]) { 
     formatter = todayFormatter; 
    } 

    return [formatter stringFromDate:aDate]; 
} 
2

나는이 오픈 소스 프로젝트를 사용하는 것이 좋습니다 수 있습니다 https://github.com/erica/NSDate-Extensions

당신은 현재의 방법을 확인 할 수 있습니다 :

+ (NSDate *) dateTomorrow 
+ (NSDate *) dateYesterday 
+0

그게 큰 확장 - 감사 Kriv. CocoaPod 지원 : 포드 'NSDate-Extensions', '~> 0.0.1' – Fraser