简体   繁体   中英

How to compare two date?

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?

 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对象还实现了记录良好的-compare:方法。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM