0

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");
    }
Curtis Boylan
  • 827
  • 1
  • 7
  • 23
  • 1
    Possible duplicate of [How to compare two dates in Objective-C](https://stackoverflow.com/questions/949416/how-to-compare-two-dates-in-objective-c) – GIJOW Mar 15 '18 at 14:45

1 Answers1

2

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

Sandeep Bhandari
  • 19,999
  • 5
  • 45
  • 78
  • Yes but if I change the date to the 15th on that it does not say the same instead it will say newDate is less – Curtis Boylan Mar 15 '18 at 15:32
  • @curtis-boylan : Thats as expected, because your today has time component for example when I use it now it shows today as 2018-03-15 15:34:33 +0000 but because your date string 2018-03-14 has no time to it when converted to date it becomes 2018-03-15 00:00:00 +0000 because obviously today is greater than your newDate it says date is less – Sandeep Bhandari Mar 15 '18 at 15:36
  • is there any way to solve this? I do not want the time component – Curtis Boylan Mar 15 '18 at 15:38