Objective c 将当前时间与一天中的两个时间字符串进行比较

Objective c 将当前时间与一天中的两个时间字符串进行比较,objective-c,nsdate,nstimeinterval,Objective C,Nsdate,Nstimeinterval,如何获得“11:30”格式的时间,以便与以下内容进行比较: strOpenTime = @"10:00"; strCloseTime = @"2:00"; 那么,如果当前时间在打开/关闭时间间隔内,如何获得上述打开/关闭时间格式的当前时间 提前谢谢 首先,必须将字符串“10:00”、“2:00”转换为当天的日期。 这可以通过以下方法实现(为简洁起见,省略错误检查): 然后转换打开和关闭时间: NSString *strOpenTime = @"10:00"; NSString *strClos

如何获得“11:30”格式的时间,以便与以下内容进行比较:

strOpenTime = @"10:00";
strCloseTime = @"2:00";
那么,如果当前时间在打开/关闭时间间隔内,如何获得上述打开/关闭时间格式的当前时间


提前谢谢

首先,必须将字符串“10:00”、“2:00”转换为当天的日期。 这可以通过以下方法实现(为简洁起见,省略错误检查):

然后转换打开和关闭时间:

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

NSDate *openTime = [self todaysDateFromString:strOpenTime];
NSDate *closeTime = [self todaysDateFromString:strCloseTime];
现在你必须考虑关闭时间可能在次日:

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];
}
然后你可以按照@visualication在他的回答中所说的继续进行:

NSDate *now = [NSDate date];

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

首先,必须将字符串“10:00”、“2:00”转换为当天的日期。 这可以通过以下方法实现(为简洁起见,省略错误检查):

然后转换打开和关闭时间:

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

NSDate *openTime = [self todaysDateFromString:strOpenTime];
NSDate *closeTime = [self todaysDateFromString:strCloseTime];
现在你必须考虑关闭时间可能在次日:

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];
}
然后你可以按照@visualication在他的回答中所说的继续进行:

NSDate *now = [NSDate date];

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

关门时间是下午2点还是次日凌晨2点?使用。。。向上投票,这是否令人震惊?到目前为止您尝试了什么?是下午2点(下午)还是次日凌晨2点关门?使用。。。向上投票,这是震惊吗?到目前为止你都尝试了什么?非常感谢马丁……)非常感谢马丁……)