2012-03-20 219 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 
}