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

时间:2015-03-16 07:09:43

标签: ios objective-c datetime nsdate

我正在试图找出检查我的约会时间是否在两个其他日期时间之间的方法,例如我从我的服务器获得当前时间“2015年3月16日14:17”所以我想检查一下是否这个日期时间是两个其他日期时间范围之间的“2015年2月4日08:00-09:00”。

3 个答案:

答案 0 :(得分:1)

我建议使用以下类方法

+ (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;
}

答案 1 :(得分:1)

当前日期:

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;
}

答案 2 :(得分:-1)

如果您有三个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];