2

I have two NSDate objects, dateOne and dateTwo. If dateTwo is later than dateone but on the same day as dateOne (ex. January 1, 2015 4:00pm and January 1, 2015 5:00pm) then I want to return that they are the same. However, as soon as dateTwo is on the next day or later (ex. January 1, 2015 and January 2, 2015), I want to return that dateOne < dateTwo.

I'm currently trying to accomplish this by doing:

- (BOOL)dateTwoLaterThanDateOne:(NSDate *)dateOne withDateTwo:(NSDate *)dateTwo {
    if([dateTwo compare: dateOne] == NSOrderedDescending) // if dateTwo is later in time than dateOne
    {
        return YES;
    }
    return NO;
}
Apollo
  • 8,874
  • 32
  • 104
  • 192
  • See http://stackoverflow.com/questions/1561554/cocoa-touch-how-do-i-see-if-two-nsdates-are-in-the-same-day, it should pretty much list all options. – Martin R Apr 21 '15 at 20:10

3 Answers3

1

Check if it's the same day with NSDateComponents.

And if it's not compare them to see if they ascend or decend.

- (BOOL)dateTwoLaterThanDateOne:(NSDate *)dateOne withDateTwo:(NSDate *)dateTwo
{
    NSCalendar* calendar = [NSCalendar currentCalendar];

    unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
    NSDateComponents* comp1 = [calendar components:unitFlags fromDate:dateOne];
    NSDateComponents* comp2 = [calendar components:unitFlags fromDate:dateTwo];
    BOOL sameDay = [comp1 day]  == [comp2 day] && [comp1 month] == [comp2 month] && [comp1 year]  == [comp2 year] ;

   return sameDay ? !sameDay : ([dateOne compare:dateTwo] == NSOrderedAscending);

}
Martin
  • 191
  • 2
  • 4
0

You could get the day component from each and compare them. Something like:

NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:[NSDate date]];

NSInteger day = [components day];

Do that for both dates and then do the comparison.

jarz
  • 732
  • 7
  • 20
0

Use this code..

NSTimeInterval secondsBetween = [dateTwo timeIntervalSinceDate: dateOne]; 
int numberOfDays = secondsBetween /(3600*24);

if (numberOfDays == 0) {
        NSLog(@"same day"); //dateOne = dateTwo
}else if (numberOfDays>0){
        NSLog(@"two > one"); //dateOne > dateTwo
}else if (numberOfDays<0){
        NSLog(@"two < one"); //dateOne < dateTwo
}

This code helps you :)

Yuyutsu
  • 2,509
  • 22
  • 38