我有这个字符串,它被传递给这个方法以产生 2 次:
周一至周五上午 7:00 - 晚上 10:00
我使用这段代码将字符串分成两次;开闭时间:
-(void)dealWithTimeStrings2:(NSString*)timeString{
<...IRRELEVANT CODE PARSING STRING INTO DATES...>
NSLog(@"openDate hours %@, openDate minutes %@", openHours, openMinutes);
NSLog(@"closeDate hours %@, closeDate minutes %@", closeHours, closeMinutes);
NSLog(@"nowDate hours %@, nowDate minutes %@", nowHours, nowMinutes);
//COMPARE HOURS
if ([openHours intValue] < [nowHours intValue] < [closeHours intValue]) {
NSLog(@"ABIERTO-dateComponents");
} else {
NSLog(@"CERRADO-dateComponents");
}
NSLog(@"open, now, close %@,%@,%@", openDate,[NSDate date], closeDate);
if ([self timeCompare:openDate until:closeDate]) {
NSLog(@"OPEN-timeCompare");
} else {
NSLog(@"CLOSED-timeCompare");
}
}
这会在控制台中生成这些日志:
someDateString 7:00 AM,10:00 PM
openDate hours 13, openDate minutes 00
closeDate hours 04, closeDate minutes 00
nowDate hours 14, nowDate minutes 51
OPEN-dateComponents
open, now, close 2000-01-01 13:00:00 +0000,2013-07-25 14:51:16 +0000,2000-01-02 04:00:00 +0000 2013-07-25 08:51:16:486
CLOSED-timeCompare
我现在想测试现在时间是否介于开盘时间和收盘时间之间。但是,如果您注意到,打开和关闭时间是在 2000-01-01 和 2000-01-02 年,而现在是在 2013-07-24 年。这是测试代码:
-(BOOL)timeCompare:(NSDate*)date1 until:(NSDate*)date2{
NSCalendar *calendar = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components =
[calendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:[NSDate date]];
NSDate *date = [calendar dateFromComponents:components];
return ([date compare:date1] == NSOrderedDescending && [date compare:date2] == NSOrderedAscending);
}
是否因为日期部分而失败?开放日期和结束日期与现在日期不同的事实是什么?