开发者

Compare two dates [duplicate]

This question already has answers here: How to compare two dates in Objective-C (14 answers) 开发者_StackOverflow中文版 Closed 9 years ago.

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).


Something like:

    NSDate* timeNow = [NSDate date];

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


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


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜