How to compare time in Objective C?
if (nowTime > 9:00 PM) && (nowTime < 7:00 AM)
{
doSomething;
}
In order to compare time, we use the compareTo() method of the LocalTime class. The compareTo() method of the class compares two LocalTime objects.
In JavaScript, we can compare two dates by converting them into numeric values to correspond to their time. First, we can convert the Date into a numeric value by using the getTime() function. By converting the given dates into numeric values we can directly compare them.
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.
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..
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With