NSDate between two given NSDates

前端 未结 3 1285
暖寄归人
暖寄归人 2020-12-03 15:57

I am interested in creating a method to find if the current date falls between certain times on any given day. It is for a scheduling program, so I want to find what event i

3条回答
  •  青春惊慌失措
    2020-12-03 16:27

    This isn't perfect, but you could use [NSDate compare:] to check your date against both boundaries:

    NSDate *firstDate = ...
    NSDate *secondDate = ...
    
    NSDate *myDate = [NSDate date];
    
    switch ([myDate compare:firstDate]) {
        case NSOrderedAscending:
            NSLog(@"myDate is older");
            // do something
            break;
        case NSOrderedSame:
            NSLog(@"myDate is the same as firstDate");
            // do something
            break;
        case NSOrderedDescending:
            NSLog(@"myDate is more recent");
            // do something
            break;
    }
    
    switch ([myDate compare:secondDate]) {
        case NSOrderedAscending:
            NSLog(@"myDate is older");
            // do something
            break;
        case NSOrderedSame:
            NSLog(@"myDate is the same as secondDate");
            // do something
            break;
        case NSOrderedDescending:
            NSLog(@"myDate is more recent");
            // do something
            break;
    }
    

    Or more briefly:

    BOOL between = NO;
    
    if (([myDate compare:firstDate] == NSOrderedDescending) &&
        ([myDate compare:secondDate] == NSOrderedAscending)) {
    
        between = YES;
    }
    

    I'm sure there's a better way to do complex date comparison, but this should work.

提交回复
热议问题