2011-04-20 235 views
10

我如何比較兩個不同的日期,以找出哪些是以後的日子?例如,在date1我會下載一些數據之後存儲一個日期,並在date2,我將存儲當前的日期。然後我需要檢查哪一個更大/更晚:類似if(date1>date2)比較兩個日期

+1

發佈提問之前,請CH eck是否使用右上角的搜索框在堆棧溢出時未被詢問。例如,搜索「比較兩個NSDate」。 – 2011-04-20 09:01:16

回答

25

喜歡的東西:

NSDate* timeNow = [NSDate date]; 

    // If less than 30 seconds, do something 
    if ([timeNow timeIntervalSinceDate:anEarlierTime] < 30.0f) 
    { 
     // Do something 
    } 
+0

thanx for ur reply,小澄清,如果時間間隔是24小時(1天)我該如何檢查? – Kiran 2011-04-20 09:14:43

+2

那麼,在一分鐘60秒,一小時60分鐘,並在24小時會給你86,400 :-) – 2011-04-20 10:42:42

24

可以使用的NSDate的比較:方法:

NSComparisonResult result = [Date2 compare:Date1]; 

if(result==NSOrderedAscending) 
    NSLog(@"Date1 is in the future"); 
else if(result==NSOrderedDescending) 
    NSLog(@"Date1 is in the past"); 
else 
    NSLog(@"Both dates are the same"); 
3
NSDateFormatter *df = [[NSDateFormatter alloc] init]; 
[df setDateFormat:@"yyyy-MM-dd"]; 
NSDate *dt1 = [[NSDate alloc] init]; 
NSDate *dt2 = [[NSDate alloc] init]; 
dt1 = [df dateFromString:@"2011-02-25"]; 
dt2 = [df dateFromString:@"2011-03-25"]; 
NSComparisonResult result = [dt1 compare:dt2]; 
switch (result) 
{ 
    case NSOrderedAscending: NSLog(@"%@ is greater than %@", dt2, dt1); break; 
    case NSOrderedDescending: NSLog(@"%@ is less %@", dt2, dt1); break; 
    case NSOrderedSame: NSLog(@"%@ is equal to %@", dt2, dt1); break; 
    default: NSLog(@"erorr dates %@, %@", dt2, dt1); break; 
} 
3

這是我用來與時區比較日期和我使用的是iOS 6的工作

 NSComparisonResult result = [timeStamp compare:serverDate]; 
     NSDateFormatter *df = [[NSDateFormatter alloc] init]; 
     [df setDateFormat:@"yyyy-MM-dd HH:mm:ss z"]; 
     switch (result) 
     { 
      case NSOrderedAscending: 
       NSLog(@"%@ is greater than %@", [df stringFromDate:serverDate], [df stringFromDate:timeStamp]); 
       break; 
      case NSOrderedDescending: 
       NSLog(@"%@ is less %@", [df stringFromDate:serverDate], [df stringFromDate:timeStamp]); 
       break; 
      case NSOrderedSame: 
       NSLog(@"%@ is equal to %@", [df stringFromDate:serverDate], [df stringFromDate:timeStamp]); 
       break; 
      default: 
       NSLog(@"erorr dates %@, %@", [df stringFromDate:serverDate], [df stringFromDate:timeStamp]); 
       break; 
     }