更新时间:2023-02-22 12:56:49
首先,您必须将字符串"10:00","2:00"转换为当前日期的日期. 这可以例如完成使用以下方法(为简便起见,省略了错误检查):
First you have to convert the strings "10:00", "2:00" to a date from the current day. This can be done e.g. with the following method (error checking omitted for brevity):
- (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];
}
然后转换您的打开和关闭时间:
Then convert your open and closing time:
NSString *strOpenTime = @"10:00";
NSString *strCloseTime = @"2:00";
NSDate *openTime = [self todaysDateFromString:strOpenTime];
NSDate *closeTime = [self todaysDateFromString:strCloseTime];
现在,您必须考虑关闭时间可能在第二天:
Now you have to consider that the closing time might be on the next day:
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在他的回答中所说的那样进行操作
And then you can proceed as @visualication said in his answer:
NSDate *now = [NSDate date];
if ([now compare:openTime] != NSOrderedAscending &&
[now compare:closeTime] != NSOrderedDescending) {
// now should be inside = Open
} else {
// now is outside = Close
}