0

I am working on an iphone app for class and my group is having some time trouble.

The idea we are working with is that we have a scheduled event (say 2:00pm) and we want to know if we are within a certain amount of time from the scheduled time (say +/- 15 minutes). So for this example if the event was at 2pm, if this event was called from 1:45-2:15pm the method would return true/yes, and otherwise, it would return false/no.

I know how to current time/date, but how do I do the part with checking to see if it is within a certain range of time from the event time? ?

So what I am going for would be a method similar to the following with currentTime getting a NSDate object for the current time and classStartTime getting a NSDate object for the start time of the class:

- (BOOL)dateInRange:(NSDate*)currentTime inRangeOf:(NSDate*)classStartTime
{
    if([currentTime <= [classStartTime dateByAddingTimeInterval:60*15]] && [currentTime >= [classStartTime dateByAddingTimeInterval:-(60*15)]])
    {
        return TRUE;
    }
    else{
        return FALSE;
    }
}

I know this doesn't work. How do I get the comparison part of the if statement to work properly

Joel
  • 23
  • 3
  • 1
    possible duplicate of [How to Check if an NSDate occurs between two other NSDates](http://stackoverflow.com/questions/1072848/how-to-check-if-an-nsdate-occurs-between-two-other-nsdates) – jscs Mar 24 '12 at 19:38

3 Answers3

0

I guess, your time is a NSDate. You could use TimeIntervalSinceDate: with the start time of your interval and check if the result is positive and smaller than your interval length.

Matthias
  • 8,018
  • 2
  • 27
  • 53
0

Use NSDate and NSDateComponents. I don't have a Mac nearby, so the following code will probably have errors in it.

NSCalendar *gregorian = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
int comp = NSHourCalendarUnit | NSMinuteCalendarUnit;
NSDateComponents *theDateComponents = [gregorian components:comp fromDate:[NSDate date]];
int hour = [theDateComponents hour];
int minute = [theDateComponents minute];
if ((hour == 13 && minute >= 45) || (hour == 14 && minute <= 15)) {
  //do your stuff
}

Hope it helps

Novarg
  • 7,390
  • 3
  • 38
  • 74
0

Find a start date and and end date with + (id)dateWithTimeInterval:(NSTimeInterval)seconds sinceDate:(NSDate *)date

then use the compare method to check that the date you are checking falls within your dates...

Grady Player
  • 14,399
  • 2
  • 48
  • 76