比较两个返回 0 或相等的 NSDates

Comparing two NSDates returning 0 or equal

我在比较两个 NSDates 时遇到问题。我没有得到正确的价值,我哪里出错了。

首先,我比较了使用 NSDatecompare 方法,它返回 0,然后我尝试通过调用 timeIntervalSince1970 将其转换为 float,这给出了相同的输出。 我做错了什么,我没有得到。

这是我所做的简单尝试。

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);
}

首先你的日期格式不对,应该是dd/MM/yyyy也用compare比较NSDate个对象

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");
}