How to compare time

后端 未结 6 566
逝去的感伤
逝去的感伤 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:48

    For checking current time or any time between two times ::

    NSCalendar *calendar = [[NSCalendar alloc]
                            initWithCalendarIdentifier:NSGregorianCalendar];
    NSCalendarUnit units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit;
    NSDateComponents *components = [calendar components:units fromDate:[NSDate date]];
    
    return [self isDateComponent:components withinStartHour:startH startMin:startM endHour:endH endMin:endM];
    

    -(BOOL)isDateComponent:(NSDateComponents*)components withinStartHour:(int)startH startMin:(int)startM endHour:(int)endH endMin:(int)endM
    {
        if (endH < startH) {
            return (  [self isDateComponent:components betweenStartHour:startH startmin:startM endHour:23 endMin:59]  ||
                    [self isDateComponent:components betweenStartHour:0 startmin:0 endHour:endH endMin:endM]  );
        }
        else {
            return [self isDateComponent:components betweenStartHour:startH startmin:startM endHour:endH endMin:endM];
        }
    
    
    }
    
    
    
    -(BOOL)isDateComponent:(NSDateComponents*)components betweenStartHour:(int)startH startmin:(int)startM endHour:(int)endH endMin:(int)endM
    {
    
        int currentH = components.hour;
        int currentM = components.minute ;
    
        DDLogVerbose(@"start : %i-%i, end : %i-%i, current:%i-%i",startH,startM,endH,endM,currentH,currentM);
        startM  = startM + startH * 60;
        endM = endM + endH * 60;
    
        currentM = components.minute + currentH*60;
    
        if ( startM <= currentM && currentM < endM ) {
            return YES;
        }
        else {
            return NO;
        }
    
    
    }
    

提交回复
热议问题