2012-08-13 56 views
0

我有以下格式2個日期:目標C - 確定哪個日期晚是日期格式

2012年8月6日

我使用下面的代碼,以試圖確定哪個日期晚是:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
     [dateFormatter setDateFormat:@"MMMM d, yyyy"]; 
     NSString *today = [dateFormatter stringFromDate:[NSDate date]]; 
     NSLog(@"%@", today); 
     NSDate *todayDate = [dateFormatter dateFromString:today]; 

     NSLog(@"TodayDate: %@", todayDate); 
     for (Job *j in appDelegate.jobs){ 
      if ([j.dueDate laterDate:todayDate]){ 
       [jobsToDisplay addObject:j]; 
      } 
     } 

但是,這段代碼不起作用,它似乎返回的日期是他們應該是一天+ 1小時。任何人都可以解釋我需要在這裏做什麼?

非常感謝,

Tysin

+0

你看過[這一個](http://stackoverflow.com/questions/1072848/how-to-check-if-an-nsdate-occurs-between-two-other-nsdates)?它可能會幫助你! – 2012-08-13 08:00:23

回答

1

您可以使用NSDate的

//If j.dueDate = today 
if ([j.dueDate compare:todayDate] == NSOrderedSame) { 
     return YES; 
    } 
//j.dueDate is latest 
    else if ([j.dueDate compare:todayDate] == NSOrderedDescending) { 
     return YES; 
    } 

compare:實例方法欲瞭解更多詳細信息https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html

https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/Reference/reference.html#//apple_ref/doc/c_ref/NSComparisonResult

1

你應該設置時區爲UTC(或任何你正在使用),以獲得準確的日期。

[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]]; 

使用下面的代碼來比較日期

[NSDate compare:obj]