How to compare two date?

倖福魔咒の 提交于 2020-01-02 17:30:19

问题


I have three dates: (1) previousDate (2) currentDate (3) nextDate, I want to check whether currentDate is later then previous date and earlier than nextDate. How do I do that?


回答1:


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



回答2:


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.




回答3:


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:"




回答4:


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
}



回答5:


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




回答6:


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


来源:https://stackoverflow.com/questions/2199488/how-to-compare-two-date

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