Search code examples
iosobjective-ccocoa-touchnsdate

Check if a NSDate object is in the past


I want to check if an NSDate object I have is in the past or now (if it's not in the future).

I've tried this but it don't working:

-(void)checkIfMuted
{
    NSDate *muteOverDate=[[NSUserDefaults standardUserDefaults] objectForKey:@"muteOverDate"];

    if ([muteOverDate timeIntervalSinceNow]<0.0) {
        self.muteEnabled=YES;
        return;
    }
    self.muteEnabled=NO;
    NSLog(@"%@\n%@",[[NSDate date] description],[muteOverDate description]);
}

NSLog print: 2016-02-10 14:55:19 +0000 2016-02-10 15:54:32 +0000

Any idea why it's not working? Thanks!


Solution

  • Use [NSDate compare:]:

    NSDate *now = [NSDate date];
    if ([now compare:muteOverDate] == NSOrderedAscending) {
        // muteOverDate is in the future
    }