比较NSDates以检查今天是否介于两者之间

时间:2011-05-09 02:57:08

标签: objective-c nsdate

感谢你们,我已成功将我的字符串数组转换为NSDates。现在我想检查今天的日期是否在我的两个日期之间(即从日期到日期)。我已经看到了以下问题,但未能在我的代码中实现它们。很棒我可以使用任何其他方法或帮助使用用户提供的解决方案。

NSDate between two given NSDates

How to Check if an NSDate occurs between two other NSDates

How can I check if an NSDate falls in between two other NSDates in an NSMutableArray

这就是我目前所拥有的:

NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:@"yyyy-MM-dd"];
NSTimeZone *tz = [NSTimeZone localTimeZone];
[format setTimeZone:tz];
NSDate *now = [[NSDate alloc] init];
NSString *todaysDate = [format stringFromDate:now];
NSLog(@"todaysDate: %@", todaysDate);

//converting string - date
int size = [appDelegate.ALLevents count];
for (NSUInteger i = 0; i < size; i++) {
    Event *aEvent = [appDelegate.ALLevents objectAtIndex:i];

    //Convert fromDate
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"dd-MM-yyyy"];
    NSDate *fromDate = [dateFormatter dateFromString:aEvent.fromDate];
    [dateFormatter setTimeZone:tz];
    NSLog(@"fromDate: %@", fromDate);

    //Convert toDate
    NSDate *toDate = [dateFormatter dateFromString:aEvent.toDate];
    NSLog(@"toDate: %@", toDate);
    [dateFormatter release];
    //Compare if today falls in between
            //codes here
    }

1 个答案:

答案 0 :(得分:5)

执行以下操作,

NSTimeInterval fromTime = [fromDate timeIntervalSinceReferenceDate];
NSTimeInterval toTime = [toDate timeIntervalSinceReferenceDate];
NSTimeInterval currTime = [[NSDate date] timeIntervalSinceReferenceDate];

NSTimeInterval基本上是一个双重类型,因此如果currTime大于1且小于日期落在这两个NSDates之间,则可以比较它。