Question

I know how to compare dates.In my case, let Date1 = 2011-10-14 & Date2 =2011-10-20 .And I want to check if 15th Oct lie between Date1 and Date2.I'm using following codes for this:

if ( [date compare:Date1] == NSOrderedDescending && [date compare:Date2] == NSOrderedAscending) {   
            //write codes

        }

But this will not check if 15th oct lie between 14th and 20th Oct.rather it check for whole date. So, How will I implement this. Thnx in advance.

Was it helpful?

Solution

I hope the following code would help you. Assuming Date1 and Date2 you have,

NSCalendar *calendar = [NSCalendar currentCalendar];
NSInteger desiredComponents = (NSDayCalendarUnit | NSMonthCalendarUnit);


NSDateComponents *firstComponents = [calendar components:desiredComponents fromDate:Date1];
NSDateComponents *secondComponents = [calendar components:desiredComponents fromDate:Date2];

NSDate *firstWOYear = [calendar dateFromComponents:firstComponents];
NSDate *SecondWOYear = [calendar dateFromComponents:secondComponents];

NSComparisonResult result = [firstWOYear compare:SecondWOYear];
if (result == NSOrderedAscending) {
    //Date1 is before Date2
} else if (result == NSOrderedDescending) {
    //Date1 is after Date2
}  else {
    //Date1 is the same day/month as Date2
}

OTHER TIPS

Where date1 = 2011-10-14 and date2 =2011-10-20 and date is the date you want to check.

Do this

if([date timeIntervalSince1970] >= [date1 timeIntervalSince1970] && [date timeIntervalSince1970] <= [date2 timeIntervalSince1970])
{
    NSLog(@"%@ lies between and including %@ and %@",date,date1,date2);
   // if you just wanna check for between (not including) two dates just remove the equal signs above in condition check
}
else
    NSLog(@"%@ does not lie between %@ and %@",date,date1,date2);

The above code will check if the date lies between and including the given two extreme dates but if you just wanna check between (but excluding) the extreme dates then simply remove the equal signs from if condition check.

Comparison ->

NSString *dateString1 = @"2011-10-14";
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
formatter.dateFormat = @"yyyy-MM-dd";

NSDate *date1 = [formatter dateFromString:dateString1];

NSString *dateString2 = @"2011-10-20";    
NSDateFormatter *formatter2 = [[NSDateFormatter alloc]init];
formatter2.dateFormat = @"yyyy-MM-dd";

NSDate *date2 = [formatter2 dateFromString:dateString2];


NSString *dateString3 = @"2011-10-15";
NSDateFormatter *formatter3 = [[NSDateFormatter alloc]init];
formatter3.dateFormat = @"yyyy-MM-dd";

NSDate *date3 = [formatter3 dateFromString:dateString3];

if ([date3 compare:date1] == NSOrderedDescending && [date3 compare:date2] == NSOrderedAscending) 
{
    NSLog(@"%@ lies b/w %@ and %@",dateString3,dateString1,dateString2);
}
else
{
    NSLog(@"Doesn't lie!");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top