I have this string which is passed to this method to produce 2 times:
Mon thru Friday 7:00 AM - 10:00 PM
And I use this code to split up the string into two times; opening and closing times:
-(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");
}
}
This produces these logs in the console:
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
I now wish to test if now time falls between the opening and closing times. But if you notice, open and close times are in the year 2000-01-01 & 2000-01-02 whereas now is in 2013-07-24. Here is the test code:
-(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);
}
Is it failing because of the date part? The fact that its a different year for the opening and closing dates vs the now date?