MD.
MD.

Reputation: 1151

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?

Upvotes: 2

Views: 8904

Answers (6)

Sharvan Kumawat
Sharvan Kumawat

Reputation: 41

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
}

Upvotes: 2

Ja͢ck
Ja͢ck

Reputation: 173562

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

Upvotes: 0

zero3nna
zero3nna

Reputation: 2918

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

Upvotes: 4

iphonedev23
iphonedev23

Reputation: 991

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

Upvotes: 8

Costique
Costique

Reputation: 23722

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

Upvotes: 0

Luca Matteis
Luca Matteis

Reputation: 29267

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.

Upvotes: 6

Related Questions