How to compare time

后端 未结 6 647
逝去的感伤
逝去的感伤 2020-12-10 07:13

How to compare time in Objective C?

if (nowTime > 9:00 PM) && (nowTime < 7:00 AM) 
{
  doSomething;
}
6条回答
  •  情书的邮戳
    2020-12-10 07:42

    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;
    }
    

    }

提交回复
热议问题