检查给定的日期时间是否在 Objective C 中的其他两个日期时间之间

Check if the given date time is between two others date time in Objective C

我想找出检查我的日期时间是否在其他两个日期时间之间的方法,例如我从我的服务器获取当前时间 "Mar 16 2015 14:17" 所以我想检查这个日期是否时间在其他两个日期时间范围之间,如 "Feb 4 2015 08:00-09:00" 或不。

如果您有三个 NSDate 个实例,请尝试使用该代码:

NSDate *beginDate, *endDate, *checkDate;
if ([beginDate laterDate:checkDate] == checkDate &&
    [checkDate laterDate:endDate] == endDate) {
    //checkDate in between beginDate and endDate
}

对于日期解析,请使用以下内容:

NSString *inputRange = @"Feb 4 2015 08:00-09:00";
NSRange firstRange = NSMakeRange(0, inputRange.length - 6);
NSString *firstDate = [inputRange substringWithRange:firstRange];
NSDateFormatter *dateFormatter = [NSDateFormatter new];
dateFormatter.dateFormat = @"MMM dd yyyy HH:mm";
NSDate *beginDate = [dateFormatter dateFromString:firstDate];
NSString *secondDate = [inputRange substringWithRange:NSMakeRange(0, inputRange.length - 11)];
secondDate = [secondDate stringByAppendingString:[inputRange substringWithRange:NSMakeRange(inputRange.length - 5, 5)]];
NSDate *endDate = [dateFormatter dateFromString:secondDate];

我会建议以下 class 方法

+ (BOOL)checkDate:(NSDate*)dateToCheck startingDate:(NSDate*)startingDate endDate:(NSDate*)endDate
{
    BOOL returnValue;

    if ([startingDate compare:endDate]==NSOrderedDescending)
    {
        returnValue = [dateToCheck compare:endDate]==NSOrderedAscending && [dateToCheck compare:startingDate]==NSOrderedDescending;

    }
    else if ([startingDate compare:endDate]==NSOrderedAscending)
    {
        returnValue = [dateToCheck compare:startingDate]==NSOrderedAscending && [dateToCheck compare:endDate]==NSOrderedDescending;
    }
    else
    {
    returnValue = [dateToCheck compare:startingDate]==NSOrderedSame && [dateToCheck compare:endDate]==NSOrderedSame;
    }
    return returnValue;
}

当前日期:

NSDate *currentDate = [NSDate date];

NSLog(@"-- %@",currentDate);

开始日期:

// 开始日期 - 2015-03-12 00:00:58 +0000

NSString *stringStartDate = @"2015-03-12 00:00:58";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
NSDate *dateStart = [formatter dateFromString:stringStartDate];

结束日期:

// 结束日期 - 2015-03-20 00:00:58 +0000

NSString *stringEndDate = @"2015-03-20 00:00:58";
NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
[formatter1 setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
NSDate *dateEnd = [formatter1 dateFromString:stringEndDate];

判断两个日期是否相差的函数

BOOL isDateCheck = [self isDate:currentDate inRangeFirstDate:dateStart lastDate:dateEnd];

函数

- (BOOL)isDate:(NSDate *)date inRangeFirstDate:(NSDate *)firstDate lastDate:(NSDate *)lastDate {
    return [date compare:firstDate] == NSOrderedDescending &&
    [date compare:lastDate]  == NSOrderedAscending;
}