我怎样才能得到像“11:30”格式的时间,以便我想将它与以下内容进行比较:
strOpenTime = @"10:00";
strCloseTime = @"2:00";
那么我怎样才能得到当前时间,如上面的开/关时间格式,如果当前时间在间隔开/关时间内,我想要?
提前致谢.. !!
答案 0 :(得分:4)
首先,您必须将字符串“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];
}
然后转换您的开启和关闭时间:
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
}