How to compare time in Objective C?
if (nowTime > 9:00 PM) && (nowTime < 7:00 AM)
{
doSomething;
}
I used the Answer Given above by rye. I just had to convert my 7:00 AM and 9:00 PM to 24 hours. Here's the method I used
/**
Willl return YES if the Restaurant is OPEN at the Moment else NO
*/
-(BOOL) isShopOpen:(NSString *) startTime closeTime:(NSString *) endTime{
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:[NSDate date]];
NSInteger currHr = [components hour];
NSInteger currtMin = [components minute];
int stHr ;
int stMin ;
int enHr ;
int enMin ;
if([startTime containsString:@"PM"]){
startTime = [startTime stringByReplacingOccurrencesOfString:@" PM" withString:@""];
stHr=[[[startTime componentsSeparatedByString:@":"] objectAtIndex:0] intValue];
stHr=stHr+12;
stMin = [[[startTime componentsSeparatedByString:@":"] objectAtIndex:1] intValue];
}else{
startTime = [startTime stringByReplacingOccurrencesOfString:@" AM" withString:@""];
stHr=[[[startTime componentsSeparatedByString:@":"] objectAtIndex:0] intValue];
stMin = [[[startTime componentsSeparatedByString:@":"] objectAtIndex:1] intValue];
}
if([endTime containsString:@"PM"]){
endTime = [endTime stringByReplacingOccurrencesOfString:@" PM" withString:@""];
enHr=[[[endTime componentsSeparatedByString:@":"] objectAtIndex:0] intValue];
enHr=enHr+12;
enMin = [[[startTime componentsSeparatedByString:@":"] objectAtIndex:1] intValue];
}else{
endTime = [endTime stringByReplacingOccurrencesOfString:@" AM" withString:@""];
enHr=[[[endTime componentsSeparatedByString:@":"] objectAtIndex:0] intValue];
enMin = [[[startTime componentsSeparatedByString:@":"] objectAtIndex:1] intValue];
}
int formStTime = (stHr*60)+stMin;
int formEnTime = (enHr*60)+enMin;
int nowTime = (currHr*60)+currtMin;
if(nowTime >= formStTime && nowTime <= formEnTime) {
// Do Some Nasty Stuff..
return YES;
}else{
return NO;
}
}