NSDate,比较两个date

好的,我已经在这里工作了几天了,而且卡住了。 我想要做的是将当前时间与预定时间进行比较。 我想要发生的是,每天在某些时候,我想要某些代码开火,但不是在我指定的时间之前。

所以,基本上如果“当前时间”是相同的或者等于“预定的时间”,那么激发这个代码。 或者激发这一行代码。

听起来很简单,但我比较两次抓取困难。

我已经格式化了一个string到像这样的date

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]; 

那么我如何比较这两个? 我已经尝试了所有我能想到的,请帮助。

你可以尝试下面的代码行吗?

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

但在你的情况下,我认为你需要保持两个date相同的格式..或一些这样的事情

  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之间做比较。

试试这个条件:

 if ([date compare:currentTime]==NSOrderedSame) { //do want you want } 

假设你的问题实际上是比较两个NSDate对象,请尝试检查下面链接的问题; 它有一些好的指针;

如何比较Objective-C中的两个date