How to compare two NSDate objects in objective C

后端 未结 6 1983
隐瞒了意图╮
隐瞒了意图╮ 2020-11-30 00:51

I have objects of Date type.

I want to compare them, and I have written an if condition in the following way:

if (([startDate1 isEqualToDate:[self g         


        
6条回答
  •  孤街浪徒
    2020-11-30 01:00

    This is a simple way to check if the date you think is larger (eg. in the future) compared to the date you think is earlier. Here is what this does.

    1. Gets the time interval (seconds and frac seconds) of both current and future date
    2. returns true if the date your testing is greater (time reference) the the other date

    Here you go

    - (BOOL)isDateGreaterThanDate:(NSDate*)greaterDate and:(NSDate*)lesserDate{
    
        NSTimeInterval greaterDateInterval = [greaterDate timeIntervalSince1970];
        NSTimeInterval lesserDateInterval = [lesserDate timeIntervalSince1970];
    
        if (greaterDateInterval > lesserDateInterval) 
            return YES;
    
        return NO;
    }
    

    This also works

    BOOL *isGreaterDateTruelyGreater = [greaterDate timeIntervalSince1970] > [lesserDate timeIntervalSince1970];
    

    The way objective-c deals with dates, is less than intuitive. Basically you can use NSTimeInterval to get the number of seconds from a point in time. It usually gives a long number, for instance as i am writing this 1351026414.640865 is the time interval from 1970.

    Point in time > point in time 1351026415.640865 > 1351026414.640865 The above is 1 second ahead, so it is true.

提交回复
热议问题