How to compare two date?

坚强是说给别人听的谎言 提交于 2019-12-06 07:34:36
iphonedev23
 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;
}

I suppose you're using the NSDate class.

You can use isEqualToDate to compare two NSDate objects. And also the earlierDate and laterDate to check currentdate is bigger than previous date and smaller than next date.

I simply used this to check it:

if ([[currentDate laterDate:nextDate] isEqualToDate:nextDate]) {
    NSLog(@"currentDate is earlier than nextDate");
}
if ([[currentDate laterDate:previousDate] isEqualToDate:currentDate]) {
    NSLog(@"currentDate is later then previousDate");
}

worked fine for me! Thx @Luca Matteis for the hint "laterDate:"

We can compare two dates easily in swift 5.0

    switch dateOld.compare(dateNew) {
    case .orderedAscending:
        // Put your code for greater
        break

    case .orderedDescending:
        // Put your code less
        break;

    case .orderedSame:
        // Put your code for equal
        break
}

NSDate objects also implement well-documented -compare: method.

Just perform two comparisons using the compare message of NSDate:

if ([previousDate compare:currentDate] == NSOrderedAscending &&
    [nextDate compare:currentDate] == NSOrderedDescending) {
    NSLog(@"current date is in between previous and next date (non-inclusive)");
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!