iOS - how to compare two times?

南楼画角 提交于 2019-12-07 10:15:26

问题


I use the following function to check if a message has expired -

- (BOOL) hasExpired:(NSDate*)myDate
{     
    if(myDate == nil)
    {
        return false;
    }
    NSDate *now = [NSDate date];
    return !([now compare:myDate] == NSOrderedAscending);
}

This works fine if I am comparing two different dates. However, it returns false if the message has expired earlier in the day today. Any ideas on how I might fix it?


回答1:


(Adding my comment as an answer:)

This should not happen, also 1 second difference between NSDate instances is enough. Add an NSLog() with both dates there to see whether they are different indeed.




回答2:


You can use system method of NSDate class to compare with current time

- (NSTimeInterval)timeIntervalSinceNow

Return value is the interval between the receiver and the current date and time. If the receiver is earlier than the current date and time, the return value is negative.

So correct code will be

- (BOOL) hasExpired:(NSDate*)myDate 
{
    return [myDate timeIntervalSinceNow] < 0.f;
}

Or if you want to compare 2 dates, use

- (NSTimeInterval)timeIntervalSinceDate:(NSDate *)anotherDate



回答3:


+(BOOL)isEndDateBigger :(NSDate *)currDate :(NSDate *)endDate {
     if ([currDate compare:endDate] == NSOrderedDescending) {
     NSLog(@"date1 is later than date2");
     return YES; 
     } else if ([currDate compare:endDate] == NSOrderedAscending) {
     return NO;
     } else {
     return NO;
   }
}



回答4:


Check to see if it is returning NSOrderedSame when it is the same day. Maybe you need to compare the time as well, separately.



来源:https://stackoverflow.com/questions/8595549/ios-how-to-compare-two-times

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!