How to compare time

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

    Theres a perfect formula for this. Just for future references

    Below is the sample code :

    NSDateComponents *components = [[NSCalendar currentCalendar] components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:[NSDate date]];
    NSInteger currHr = [components hour];
    NSInteger currtMin = [components minute];
    
    NSString *startTime = @"21:00";
    NSString *endTime = @"07:00";
    
    int stHr = [[[startTime componentsSeparatedByString:@":"] objectAtIndex:0] intValue];
    int stMin = [[[startTime componentsSeparatedByString:@":"] objectAtIndex:1] intValue];
    int enHr = [[[endTime componentsSeparatedByString:@":"] objectAtIndex:0] intValue];
    int enMin = [[[endTime componentsSeparatedByString:@":"] objectAtIndex:1] intValue];
    
    int formStTime = (stHr*60)+stMin;
    int formEnTime = (enHr*60)+enMin;
    
    int nowTime = (int)((currHr*60)+currtMin);
    
    if(nowTime >= formStTime && nowTime <= formEnTime) {
        // Do Some Nasty Stuff..
    }
    

提交回复
热议问题