NSDate *date = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
[dateFormat setDateFormat:@"MM/dd/yyyy"];
NSLog([@"today is " stringByAppendingString:[dateFormat stringFromDate:date]]);
NSLog([@"firstBirthdayDate is " stringByAppendingString:[dateFormat stringFromDate:firstBirthdayDate]]);
NSLog([@"secondBirthdayDate is " stringByAppendingString:[dateFormat stringFromDate:secondBirthdayDate]]);
if ([firstBirthdayDate isEqualToDate:secondBirthdayDate])
NSLog(@"First date is the same as second date");
if (firstBirthdayDate < date)
NSLog(@"First date is earlier than today");
else
NSLog(@"First date is later than today");
if (secondBirthdayDate < date)
NSLog(@"Second date is earlier than today");
firstBirthdayDate is 01/23/2012secondBirthdayDate is 01/23/2012Here's what I get in the log:
First date is the same as second date
First date is later than today
Second date is earlier than today
I think I'm going crazy...
Use if ([date1 isEqualToDate:date2]) for comparing two dates or else you can use the following,
if ([date1 compare:date2] == NSOrderedSame)
if ([date1 compare:date2] == NSOrderedAscending)
if ([date1 compare:date2] == NSOrderedDescending)
>, < or = are only for comparing non-pointers. Basically my understanding is that when you are using these operators, it might be comparing the memory addresses rather than the values in it. So you will get unexpected results.
Logically, this is how it works:
if (obj1 > obj2) {
return NSOrderedDescending;
}
if (obj1 < obj2) {
return NSOrderedAscending;
}
if (obj1 == obj2) {
return NSOrderedSame;
}
You can use any of the compare statements to compare dates.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With