Search code examples
iosobjective-cnsdatensdateformatter

NSDate Comparing Two Dates Not Working


I am using the following code to compare two dates, I would expect the code to return "newDate is less" as todays date is 2018-03-16 but instead it is returning both dates are the same. Any way to solve this? I know it must be very simple just can't pin my finger on it.

    NSDateFormatter *dateFormatter=[NSDateFormatter new];
    NSDate *today = [NSDate date]; 
    NSDate *newDate = [dateFormatter dateFromString:@"2018-03-14"]; 

    if([today compare:newDate]==NSOrderedAscending){
        NSLog(@"today is less");
    }
    else if([today compare:newDate]==NSOrderedDescending){
        NSLog(@"newDate is less");
    }
    else{
        NSLog(@"Both dates are same");
    }

Solution

  • Thats because your newDate is nil. You have not specified the date format to the dateFormatter.

    NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"]; //missing statement in your code
    NSDate *today = [NSDate date];
    NSDate *newDate = [dateFormatter dateFromString:@"2018-03-14"];
    

    Now it prints output as expected

    EDIT 1:

    As OP wants to compare dates without any time component am updating the code to do the same

    NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *today = [NSDate date];
    NSString *todayString = [dateFormatter stringFromDate:today];
    today = [dateFormatter dateFromString:todayString];
    NSDate *newDate = [dateFormatter dateFromString:@"2018-03-15"];
    
    if([today compare:newDate]==NSOrderedAscending){
        NSLog(@"today is less");
    }
    else if([today compare:newDate]==NSOrderedDescending){
        NSLog(@"newDate is less");
    }
    else{
        NSLog(@"Both dates are same");
    }
    

    Now the code shows Both dates are same when new date specified as 2018-03-15 and shows newDate is less when new date is specified as 2018-03-14

    Hope this helps