0

I have an 2 NSDates, a startdate and enddate. These dates have the following format.

startDate = 2013-02-22 12:00:00 +0000; endDate = 2013-02-25 13:00:00 +0000;

Now I want to compare these dates. Therefore I've this code.

if([event.startDate isEqualToDate:event.endDate]){
     NSLog(@"event %@ is in the same day",event.title);
}else{
     NSLog(@"event %@ is NOT in the same day",event.title);
}

But the problem is that it always gets in the else-statement. I want that if the startDate and endDate are in the same day,month and year they give me the first NSLog else they give me the second NSLog

Any help?

Dr.Kameleon
  • 22,532
  • 20
  • 115
  • 223
Steaphann
  • 2,797
  • 6
  • 50
  • 109

2 Answers2

1

Try this :

if ([event.startDate compare:event.endDate]==NSOrderedSame)
{
    // The same
}
else
{
    // Not the same
}

EDIT : And now that I've noticed (@trojanfoe's correct comment) : make sure the time is equal too, or just remove it from your NSDate objects.

Dr.Kameleon
  • 22,532
  • 20
  • 115
  • 223
  • isEqualToDate: method detects sub-second differences between dates. If you want to compare dates with a less fine granularity, use timeIntervalSinceDate: to compare the two dates. – Mrunal Feb 13 '13 at 08:35
0
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *startDateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit) fromDate:startDate];
    NSDateComponents *endDateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit) fromDate:endDate];
    NSDate *startDate = [calendar dateFromComponents:startDateComponents];
    NSDate *endDate = [calendar dateFromComponents:endDateComponents];

    if([startDate isEqualToDate:endDate])
    {
        NSLog(@"event %@ is in the same day",event.title);
    }
    else{
        NSLog(@"event %@ is NOT in the same day",event.title);
    }
Anil Varghese
  • 42,757
  • 9
  • 93
  • 110