如何比较两个不同的日期以找出哪个日期更晚?例如,在date1
中,我将在下载一些数据后存储一个日期,而在date2
中,我将存储当前日期。然后我需要检查哪一个更大/更晚:类似if(date1>date2)
。
答案 0 :(得分:25)
类似的东西:
NSDate* timeNow = [NSDate date];
// If less than 30 seconds, do something
if ([timeNow timeIntervalSinceDate:anEarlierTime] < 30.0f)
{
// Do something
}
答案 1 :(得分:24)
你可以使用NSDate的compare:方法:
NSComparisonResult result = [Date2 compare:Date1];
if(result==NSOrderedAscending)
NSLog(@"Date1 is in the future");
else if(result==NSOrderedDescending)
NSLog(@"Date1 is in the past");
else
NSLog(@"Both dates are the same");
答案 2 :(得分:3)
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd"];
NSDate *dt1 = [[NSDate alloc] init];
NSDate *dt2 = [[NSDate alloc] init];
dt1 = [df dateFromString:@"2011-02-25"];
dt2 = [df dateFromString:@"2011-03-25"];
NSComparisonResult result = [dt1 compare:dt2];
switch (result)
{
case NSOrderedAscending: NSLog(@"%@ is greater than %@", dt2, dt1); break;
case NSOrderedDescending: NSLog(@"%@ is less %@", dt2, dt1); break;
case NSOrderedSame: NSLog(@"%@ is equal to %@", dt2, dt1); break;
default: NSLog(@"erorr dates %@, %@", dt2, dt1); break;
}
答案 3 :(得分:3)
这是我用来比较日期和时区,并使用iOS 6
为我工作 NSComparisonResult result = [timeStamp compare:serverDate];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd HH:mm:ss z"];
switch (result)
{
case NSOrderedAscending:
NSLog(@"%@ is greater than %@", [df stringFromDate:serverDate], [df stringFromDate:timeStamp]);
break;
case NSOrderedDescending:
NSLog(@"%@ is less %@", [df stringFromDate:serverDate], [df stringFromDate:timeStamp]);
break;
case NSOrderedSame:
NSLog(@"%@ is equal to %@", [df stringFromDate:serverDate], [df stringFromDate:timeStamp]);
break;
default:
NSLog(@"erorr dates %@, %@", [df stringFromDate:serverDate], [df stringFromDate:timeStamp]);
break;
}