Update: Please note that this decision is relevant to your case and assumes that the storeβs opening hours do not take two days. For example, it will not work if the opening hour runs from Monday from 21:00 to Tuesday at 10 am. From 10 pm after 9 pm, but not earlier than 10 am (during the day). Therefore, keep this in mind.
I have prepared a function that will tell you if the time of one date is between two other dates (it ignores the year, month and day). There is also a second helper function that gives you a new NSDate with the year, month, and day components "neutralized" (for example, set to some static value).
The idea is to set the components of the year, month, and day to be the same between all dates so that the comparison is based only on time.
I am not sure if this is the most efficient approach, but it works.
- (NSDate *)dateByNeutralizingDateComponentsOfDate:(NSDate *)originalDate { NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease]; // Get the components for this date NSDateComponents *components = [gregorian components: (NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate: originalDate]; // Set the year, month and day to some values (the values are arbitrary) [components setYear:2000]; [components setMonth:1]; [components setDay:1]; return [gregorian dateFromComponents:components]; } - (BOOL)isTimeOfDate:(NSDate *)targetDate betweenStartDate:(NSDate *)startDate andEndDate:(NSDate *)endDate { if (!targetDate || !startDate || !endDate) { return NO; } // Make sure all the dates have the same date component. NSDate *newStartDate = [self dateByNeutralizingDateComponentsOfDate:startDate]; NSDate *newEndDate = [self dateByNeutralizingDateComponentsOfDate:endDate]; NSDate *newTargetDate = [self dateByNeutralizingDateComponentsOfDate:targetDate]; // Compare the target with the start and end dates NSComparisonResult compareTargetToStart = [newTargetDate compare:newStartDate]; NSComparisonResult compareTargetToEnd = [newTargetDate compare:newEndDate]; return (compareTargetToStart == NSOrderedDescending && compareTargetToEnd == NSOrderedAscending); }
I used this code to verify it. You can see that the year, month and days are set to some random values ββand do not affect the time check.
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease]; [dateFormatter setDateFormat:@"yyyy:MM:dd HH:mm:ss"]; NSDate *openingDate = [dateFormatter dateFromString:@"2012:03:12 12:30:12"]; NSDate *closingDate = [dateFormatter dateFromString:@"1983:11:01 17:12:00"]; NSDate *targetDate = [dateFormatter dateFromString:@"2034:09:24 14:15:54"]; if ([self isTimeOfDate:targetDate betweenStartDate:openingDate andEndDate:closingDate]) { NSLog(@"TARGET IS INSIDE!"); }else { NSLog(@"TARGET IS NOT INSIDE!"); }
source share