Saheb Singh Saheb Singh - 2 months ago 7
Objective-C Question

Comparing two NSDates returning 0 or equal

I am facing problem in comparing two

NSDates
. I am not getting proper value, where I am going wrong.

First I compared using
compare
method of
NSDate
which was returning 0 and next I tried to convert it into float by calling
timeIntervalSince1970
which is giving same output.
What I am doing wrong, I am not getting.

Here is the simple try which I did.

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"dd/MM/YYYY"];

NSString *date1String = @"01/01/2016";
NSString *date2String = @"03/01/2016";

float date1 = [[formatter dateFromString:date1String] timeIntervalSince1970];
float date2 = [[formatter dateFromString:date2String] timeIntervalSince1970];

if (date1 > date2) {
NSLog(@"date1 is later than date2");

} else if (date1 < date2){
NSLog(@"date1 is earlier than date2");

} else {
NSLog(@"date1 is Equal date2 %f \n%f",date1,date2);
}

Answer

First of all your date formate is wrong, it should be dd/MM/yyyy also use compare to compare to NSDate objects.

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"dd/MM/yyyy"];

NSString *date1String = @"01/01/2016";
NSString *date2String = @"03/01/2016";

NSDate *date1 = [formatter dateFromString:date1String];
NSDate *date2 = [formatter dateFromString:date2String];
if ([date1 compare:date2] == NSOrderedDescending) {
    NSLog(@"date1 is later than date2");
} else if ([date1 compare:date2] == NSOrderedAscending) {
    NSLog(@"date1 is earlier than date2");
} else {
    NSLog(@"dates are the same");
} 
Comments