このメソッドに渡されて 2 回生成されるこの文字列があります。
月~金曜日 午前 7:00 ~ 午後 10:00
そして、このコードを使用して文字列を 2 回に分割します。開館時間と閉館時間:
-(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);
}
日付部分が原因で失敗していますか?開始日と終了日が現在の日付とは異なる年であるという事実は?