如果声明日期

我想要做的是使用大于小于标志的日期制作一个if语句。 由于某种原因,只有大于号的工作。 这是我的代码:

NSDate *currDate = [NSDate date]; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init]; [dateFormatter setDateFormat:@"HHmm"]; NSString *dateString = [dateFormatter stringFromDate:currDate]; NSLog(@"%@",dateString); if (dateString  @"0800") { NSLog(@"Homeroom"); } else { NSLog(@"no"); } 

如果时间是8:03,则此代码的输出将是:

 2013-04-08 08:03:47.956 Schedule2.0[13200:c07] 0803 2013-04-08 08:03:47.957 Schedule2.0[13200:c07] no 

如果我是这样做的话只有那么大,那么这样的标志:

 if (dateString > @"0800") { NSLog(@"Homeroom"); } else { NSLog(@"no"); } 

输出将是这样的:

 2013-04-08 08:03:29.748 Schedule2.0[14994:c07] 0803 2013-04-08 08:03:29.749 Schedule2.0[14994:c07] Homeroom 

创建一个NSDate对象,时间为8:10,另一个为8:00。 现在,您可以将给定日期与这两个日期进行比较

 if(([date0800 compare:date] == NSOrderingAscending) && [date0810 compare:date] == NSOrderingDescending) ) { // date is between the other } 

创建边界日期,你可以做到这一点

 NSDate *date = [NSDate date]; // now NSDateComponents *components = [[NSCalendar currentCalendar] components:( NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit ) fromDate:date]; components.hour = 8; components.minute = 0; NSDate *date0800 = [[NSCalendar currentCalendar] dateFromComponents: components]; components.minute = 10; NSDate *date0810 = [[NSCalendar currentCalendar] dateFromComponents: components]; 

如果你坚持使用像<>这样的运算符,你可以使用日期对象的时间间隔。

 if(([date0800 timeIntervalSince1970] < [date timeIntervalSince1970]) && ([date0810 timeIntervalSince1970] > [date timeIntervalSince1970])) { // date lays between the other two } 

但要注意检查== ,因为舍入错误可能会导致错误。

在这里,您将使用<>比较字符串对象,这与您期望的不一样。 您可以使用NSDateComponents来获取时间和分钟来比较它们:

 NSDate *today = [NSDate date]; NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSDateComponents *components = [gregorian components:(NSHourCalendarUnit | NSMinuteCalendarUnit ) fromDate:today]; NSInteger hour = [weekdayComponents hour]; NSInteger minutes = [weekdayComponents minute]; BOOL homeroom = (hour == 8) && (minute < 10); 

或者,您可以使用NSDateFormater并使用compare:函数为8:10和8:00创建特定的NSDate。

NSString对象是对象,当您使用C比较运算符(==,>,<等)比较对象时,您要比较它们的地址,而不是它们的值。 您需要使用compare ,例如:

 if ([dateString compare:@"0810"] == NSOrderedAscending && [dateString compare:@"0800"] == NSOrderedDescending) { ... 

虽然如果你想比较日期和时间,我建议在大多数情况下转换为NSDate对象。

您不能使用>或<来比较字符串对象。 这实际上比较了指针,所以我们不会理解为什么>‘工作’和<'没有'。

对于这种日期比较,请使用NSDateComponents NSDateComponents Reference

这是我在NSDate上写的类别的要点。 我发现它使我的代码更具可读性。

https://gist.github.com/nall/5341477

 @interface NSDate(SZRelationalOperators) -(BOOL)isLessThan:(NSDate*)theDate; -(BOOL)isLessThanOrEqualTo:(NSDate*)theDate; -(BOOL)isGreaterThan:(NSDate*)theDate; -(BOOL)isGreaterThanOrEqualTo:(NSDate*)theDate; @end