2012-03-20 215 views
11

好的,我一直在這個工作了幾天,現在卡住了。我想要做的是將當前時間與預定時間進行比較。我想要發生的是,每天在某些時候我想要某些代碼開火,但不是在我指定的時間之前。NSDate,比較兩個日期

因此,基本上如果「當前時間」等於或者等於「預定時間」,則啓動該代碼。或者激發這一行代碼。

聽起來很簡單,但我無法抓住比較兩次。

我已經格式化字符串爲日期,像這樣

 NSString* dateString = @"11:05 PM"; 
     NSDateFormatter* firstDateFormatter = [[[NSDateFormatter alloc] init] autorelease]; 
     [firstDateFormatter setDateFormat:@"h:mm a"]; 
     [firstDateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]; 
     NSDate* date = [firstDateFormatter dateFromString:dateString]; 
     NSLog(@"date %@",date); 

然後我抓住當前的時間,像這樣

NSDate *currentTime = [NSDate dateWithTimeIntervalSinceNow:[[NSTimeZone localTimeZone]  secondsFromGMT]]; 
NSDateComponents* comps = [[NSCalendar currentCalendar] 
          components: NSHourCalendarUnit |NSMinuteCalendarUnit 
           |NSSecondCalendarUnit fromDate:currentTime]; 
[[NSCalendar currentCalendar] dateFromComponents:comps]; 

讓我怎麼比較這兩個時間?我嘗試了所有我能想到的,請幫助。

回答

21

你可以試試下面的代碼行?

switch ([dateOne compare:dateTwo]){ 
    case NSOrderedAscending: 
      NSLog(@"NSOrderedAscending"); 
    break; 
    case NSOrderedSame: 
      NSLog(@"NSOrderedSame"); 
    break; 
    case NSOrderedDescending: 
     NSLog(@"NSOrderedDescending"); 
    break; 
} 

但在你的情況,我認爲你必須保持兩個日期相同的格式..或一些這樣的事

NSDateComponents *components = [[NSCalendar currentCalendar] components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:[NSDate date]]; 
    [components setHour:23];//change your time to 24hrs formate 
    [components setMinute:05]; 
    [components setSecond:00]; 


    NSDate *dateOne = [[NSCalendar currentCalendar] dateFromComponents:components]; 

    components = [[NSCalendar currentCalendar] components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:[NSDate date]]; 

    NSDate *dateTwo = [[NSCalendar currentCalendar] dateFromComponents:components]; 

,做dateOne和dateTwo之間的比較。

3

試試這個條件:

if ([date compare:currentTime]==NSOrderedSame) { 

     //do want you want 
}