如果使用日期声明(If statement with dates)

2019-08-20 11:50发布

我所要做的是做一个if语句用大于小于标志日期。 出于某种原因,只比标志工程越大。 这里是我的代码:

NSDate *currDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"HHmm"];
NSString *dateString = [dateFormatter stringFromDate:currDate];
NSLog(@"%@",dateString);

if (dateString < @"0810" && 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

Answer 1:

创建的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
}

但要注意检查==就可以了,因为它可能是错误的,由于舍入误差。



Answer 2:

在这里,你是在比较字符串对象,用<> ,它不会做你期待什么。 您可以使用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);

或者你可以8:10和8:00使用NSDateFormater和使用用于创建一个特定的NSDate compare:功能。



Answer 3:

NSString对象是对象,并且当与C比较操作符(==,>,<等)你是比较它们的地址,而不是它们的值进行比较的对象。 您需要使用compare ,如:

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

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



Answer 4:

不能使用>或<String对象进行比较。 这实际上比较的指针,所以我们不会进入为什么>“作品”和<“不”。

对于这种日期比较的使用NSDateComponents NSDateComponents参考



Answer 5:

这里有一个I类上的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


文章来源: If statement with dates