Sveta Sveta - 6 months ago 16
Objective-C Question

How to compare time

How to compare time on ObjC?

if (nowTime > 9:00 PM) && (nowTime < 7:00 AM)
{
doSomething;
}

Answer

If you want to get the current hour and compare it to some times, you're going to have to use NSDate, NSDateComponents, and NSCalendar.

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
}

That will check if the time is between 9:00 PM and 7:00 AM. Of course, if you're going to want different times you'll have to change the code a little.


Read about NSDate, NSDateComponents, and NSCalendar to learn more.

Comments