George Friday
George Friday

Reputation: 585

Check If Date Is Between Two Dates

Good afternoon,

How do you check if a date is between two dates? I know I have to convert the data strings to NSDate values first:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM/dd/yyyy"];

NSDate *date1 = [dateFormatter dateFromString:@"01/01/2001"];
NSDate *date2 = [dateFormatter dateFromString:@"01/01/2010"];

NSDate *userDate = [dateFormatter dateFromString:@"12/12/2001"];

And then I have to use an if-statement, but I am not quite sure how to go about it. Here is what I need:

if (userDate is between date1 and date2) {

}

Any help with the if-statement would be appreciated. Thank you!

Upvotes: 1

Views: 2034

Answers (3)

Daniele Bernardini
Daniele Bernardini

Reputation: 1536

of the top of my head so check the syntax ;-)

if (([userDate laterDate: date1] == userDate) && ([userDate laterDate: date2] == date2)){
}

Upvotes: 2

Metabble
Metabble

Reputation: 11841

if(([userDate compare: date1] ==  NSOrderedDescending) && ([userDate compare: date2] == NSOrderedAscending)){
//do something
}

Upvotes: 1

indragie
indragie

Reputation: 18122

Use NSDate -compare::

if (([date1 compare:userDate] == NSOrderedAscending) && ([date2 compare:userDate] == NSOrderedDescending)) {
        // Do something
}

Upvotes: 5

Related Questions