11

Ok, I have been working on this for a couple of days now and am stuck. What I am trying to do is compare the current time with a predetermined time. What I want to happen is, Everyday at certain times I want certain code to fire, but not before the time of day that I specify.

so, basically if the "current time" is the same or equal to "predetermined time" then fire this code. Or fire this line of code.

Sounds simple, but I am having trouble grabbing comparing the two times.

I have formatted a string to a date like so

     NSString* dateString = @"11:05 PM";
        NSDateFormatter* firstDateFormatter = [[[NSDateFormatter alloc] init] autorelease];
        [firstDateFormatter setDateFormat:@"h:mm a"];
        [firstDateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
        NSDate* date = [firstDateFormatter dateFromString:dateString];
        NSLog(@"date %@",date);

then i grab the current time like so

   NSDate *currentTime = [NSDate dateWithTimeIntervalSinceNow:[[NSTimeZone localTimeZone]     secondsFromGMT]];
NSDateComponents* comps = [[NSCalendar currentCalendar] 
                           components: NSHourCalendarUnit |NSMinuteCalendarUnit 
                                |NSSecondCalendarUnit fromDate:currentTime];
 [[NSCalendar currentCalendar] dateFromComponents:comps];

SO how do I compare these two times? I have tried everything I can think of, please help.

Mike Owens
  • 936
  • 3
  • 8
  • 20

3 Answers3

21

Can you try below lines of code?

switch ([dateOne compare:dateTwo]){
     case NSOrderedAscending:
          NSLog(@"NSOrderedAscending");
    break;
    case NSOrderedSame:
          NSLog(@"NSOrderedSame");
    break;
    case NSOrderedDescending:
         NSLog(@"NSOrderedDescending");
    break;
}

But in your case I think you need to keep both dates in same format ..or some thing like this

 NSDateComponents *components = [[NSCalendar currentCalendar] components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:[NSDate date]];
    [components setHour:23];//change your time to 24hrs formate 
    [components setMinute:05];
    [components setSecond:00];


    NSDate *dateOne = [[NSCalendar currentCalendar] dateFromComponents:components];

    components = [[NSCalendar currentCalendar] components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:[NSDate date]];

     NSDate *dateTwo = [[NSCalendar currentCalendar] dateFromComponents:components];

and do comparison between dateOne and dateTwo.

Raj
  • 5,895
  • 4
  • 27
  • 48
3

Try this condition:

if ([date compare:currentTime]==NSOrderedSame) {

         //do want you want
}
Caleb
  • 124,013
  • 19
  • 183
  • 272
nithin
  • 2,457
  • 1
  • 30
  • 50
0

Assuming your issue is actually comparing the two NSDate objects, try checking out the question linked below; it has some good pointers;

How to compare two dates in Objective-C

Community
  • 1
  • 1
Madhu
  • 2,429
  • 16
  • 31