Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare time

How to compare time in Objective C?

if (nowTime > 9:00 PM) && (nowTime < 7:00 AM) 
{
  doSomething;
}
like image 986
Sveta Avatar asked Mar 22 '11 08:03

Sveta


People also ask

Can you compare time in Java?

In order to compare time, we use the compareTo() method of the LocalTime class. The compareTo() method of the class compares two LocalTime objects.

Can we compare time in JavaScript?

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.


Video Answer


2 Answers

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.

like image 90
Itai Ferber Avatar answered Nov 15 '22 07:11

Itai Ferber


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..
}
like image 42
Rye Avatar answered Nov 15 '22 08:11

Rye