如何比较时间

Sve*_*eta 6 time compare objective-c

如何比较Objective C中的时间?

if (nowTime > 9:00 PM) && (nowTime < 7:00 AM) 
{
  doSomething;
}
Run Code Online (Sandbox Code Playgroud)

Ita*_*ber 16

如果你想获得当前的小时和比较,有些时候,你将不得不使用NSDate,NSDateComponentsNSCalendar.

NSDateComponents *components = [[NSCalendar currentCalendar] components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:[NSDate date]];
NSInteger currentHour = [components hour];
NSInteger currentMinute = [components minute];
NSInteger currentSecond = [components second];

if (currentHour < 7 || (currentHour > 21 || currentHour == 21 && (currentMinute > 0 || currentSecond > 0))) {
    // Do Something
}
Run Code Online (Sandbox Code Playgroud)

这将检查时间是否在晚上9点到早上7点之间.当然,如果你想要不同的时间,你将不得不稍微改变代码.


阅读有关NSDate,NSDateComponentsNSCalendar的信息以了解更多信息.


Rye*_*Rye 10

这是一个完美的公式.仅供将来参考

以下是示例代码:

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..
}
Run Code Online (Sandbox Code Playgroud)