将当前时间与两个时间字符串进行比较

jig*_*igs 0 objective-c nsdate nstimeinterval

我怎样才能获得像“11:30”这样的时间,以便我想将它与以下内容进行比较:

strOpenTime = @"10:00";
strCloseTime = @"2:00";
Run Code Online (Sandbox Code Playgroud)

那么我怎样才能获得像上面打开/关闭时间格式一样的当前时间,我想要当前时间是否在打开/关闭时间间隔内?

提前致谢..!!

Mar*_*n R 5

首先,你必须从转换字符串“10:00”,“2:00”的日期当天。这可以通过例如以下方法来完成(为简洁起见省略了错误检查):

- (NSDate *)todaysDateFromString:(NSString *)time
{
    // Split hour/minute into separate strings:
    NSArray *array = [time componentsSeparatedByString:@":"];

    // Get year/month/day from today:
    NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *comp = [cal components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:[NSDate date]];

    // Set hour/minute from the given input:
    [comp setHour:[array[0] integerValue]];
    [comp setMinute:[array[1] integerValue]];

    return [cal dateFromComponents:comp];
}
Run Code Online (Sandbox Code Playgroud)

然后转换您的开放和关闭时间:

NSString *strOpenTime = @"10:00";
NSString *strCloseTime = @"2:00";

NSDate *openTime = [self todaysDateFromString:strOpenTime];
NSDate *closeTime = [self todaysDateFromString:strCloseTime];
Run Code Online (Sandbox Code Playgroud)

现在您必须考虑关闭时间可能在第二天:

if ([closeTime compare:openTime] != NSOrderedDescending) {
    // closeTime is less than or equal to openTime, so add one day:
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *comp = [[NSDateComponents alloc] init];
    [comp setDay:1];
    closeTime = [cal dateByAddingComponents:comp toDate:closeTime options:0];
}
Run Code Online (Sandbox Code Playgroud)

然后你可以按照@visualication 在他的回答中所说的那样继续:

NSDate *now = [NSDate date];

if ([now compare:openTime] != NSOrderedAscending &&
    [now compare:closeTime] != NSOrderedDescending) {
    // now should be inside = Open
} else {
    // now is outside = Close
}
Run Code Online (Sandbox Code Playgroud)