Compare two dates [duplicate]

2020-02-20 03:43发布

问题:

How can I compare two different dates to find out which is the later date? For example, in date1 I will store one date after downloading some data, and in date2, I will store the current date. Then I need to check which one is greater/later: something like if(date1>date2).

回答1:

Something like:

    NSDate* timeNow = [NSDate date];

    // If less than 30 seconds, do something
    if ([timeNow timeIntervalSinceDate:anEarlierTime] < 30.0f)
    {
        // Do something
    }


回答2:

you can use NSDate's compare: method:

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


回答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;
}


回答4:

This is what I used for comparing dates with timezones, and worked for me using 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;
        }